asp.net接続SQLデータベースを検索して結果をWebページに表示する(2つの方法)

3224 ワード

ASP.NETでは、C#を使用してSQLデータベースに接続し、SQL文を使用してクエリーします.以前はC#に触れたことがありませんでしたが、最近使って、2日間模索してやっと実行しました.
2つの方法があります:(第1の方法は安全ではありませんて、私もよく分かりません^^)
1つ目の方法:
 
  
// ASP.NET Web , Page_load ,
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[" "]);
}
}
}

2つ目の方法は安全ですが、面倒です.
 
  
//1、 Web.config



// ,




//2、
sCon = ConfigurationManager.AppSettings["connect"];
if (string.IsNullOrEmpty(sCon))
{
Response.Write(" !");
}
con = new SqlConnection(sCon);
//3、
if (con.State == ConnectionState.Closed)
con.Open();
//4、
public SqlDataReader ExcuteDataReader(string strTxt, CommandType cmdType, SqlParameter[] Params)
{
SqlDataReader dr = null;
if (con.State == ConnectionState.Closed)
{
Response.Write(" !");
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、
//SQL ,id=N'id', N 。
string s = "select * from table where id=N'" + id + "'";
SqlParameter[] Params1 = null;
//
SqlDataReader select_result = null;
select_result = a.ExcuteDataReader(s, CommandType.Text, Params1);
string ss = "";
while (select_result.Read())
{
//
ss = ss + " :" + select_result[0] + ", :" + select_result[1] + "; ";
}
//
Response.Write(ss);