欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

asp.net連接查詢SQL數(shù)據(jù)庫并把結(jié)果顯示在網(wǎng)頁上(2種方法)

 更新時(shí)間:2013年04月26日 15:51:49   作者:  
使用C#連接SQL數(shù)據(jù)庫,并使用SQL語句查詢,摸索了兩天終于運(yùn)行起來了,接下來為大家分享下兩種連接方法,感興趣的朋友可以參考下哈,希望可以幫助到你
在ASP.NET中,使用C#連接SQL數(shù)據(jù)庫,并使用SQL語句查詢,以前從來沒有接觸過C#,最近用到了,摸索了兩天終于運(yùn)行起來了,Mark一下,不喜勿噴

有兩種方法:(說的是第一種方法不安全,我也不清楚^_^)
第一種方法
復(fù)制代碼 代碼如下:

//建立ASP.NET Web 應(yīng)用程序,直接在Page_load函數(shù)中加入一下代碼,貌似就可以用了
public void Page_Load(object sender, EventArgs e)
{
using (SqlConnection con = new SqlConnection("Data Source=.;uid=sa;pwd=sa;Database=NorthWind"))
{
string username = "forever";
string strSQL = "select * from table where name='" + username + "'";
SqlDataAdapter adapter = new SqlDataAdapter(strSQL, con);
DataSet ds = new DataSet();
adapter.Fill(ds);
foreach (DataRowView drv in ds.Tables[0].DefaultView)
{
Response.Write(drv["第一個字段"]+"|"+drv["第二個字段"]);
}
}
}

第二種方法說的比較安全,就是比較麻煩
復(fù)制代碼 代碼如下:

//1、修改Web.config配置文件
<configuration>
<connectionStrings>
</connectionStrings>
//下面三行是添加的內(nèi)容,即連接數(shù)據(jù)庫的信息
<appSettings>
<add key="connect" value="server=.;database=NorthWind;uid=sa;pwd=sa;"/>
</appSettings>
<system.web>
//2、連接數(shù)據(jù)庫
sCon = ConfigurationManager.AppSettings["connect"];
if (string.IsNullOrEmpty(sCon))
{
Response.Write("連接字符串為空!");
}
con = new SqlConnection(sCon);
//3、打開數(shù)據(jù)庫
if (con.State == ConnectionState.Closed)
con.Open();
//4、查詢函數(shù)
public SqlDataReader ExcuteDataReader(string strTxt, CommandType cmdType, SqlParameter[] Params)
{
SqlDataReader dr = null;
if (con.State == ConnectionState.Closed)
{
Response.Write("數(shù)據(jù)庫的連接沒有打開!");
return dr;
}
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
cmd.CommandText = strTxt;
cmd.CommandType = cmdType;
if (Params != null)
{
foreach (SqlParameter param in Params)
{
if (param != null) cmd.Parameters.Add(param);
}
}
#if NOTALLOWEXCEPTION
try
#endif
{
if (cmd.ExecuteScalar() != null)
{
dr = cmd.ExecuteReader();
}
}
#if NOTALLOWEXCEPTION
catch(SqlException se)
{
_objToShowErr = se;
_sError = se.Message;
return null;
}
finally
#endif
{
cmd.Dispose();
}
return dr;
}
//5、執(zhí)行查詢
//SQL語句,id=N'id',加個N是為了能識別中文字符。
string s = "select * from table where id=N'" + id + "'";
SqlParameter[] Params1 = null;
//保存結(jié)果
SqlDataReader select_result = null;
select_result = a.ExcuteDataReader(s, CommandType.Text, Params1);
string ss = "";
while (select_result.Read())
{
//根據(jù)自己的字段數(shù)寫
ss = ss + "第一個字段:" + select_result[0] + ", 第二個字段:" + select_result[1] + "; ";
}
//測試輸出
Response.Write(ss);

相關(guān)文章

最新評論