asp.net连接查询SQL数据库并把结果显示在网页上(2种方法)
//1、修改Web.config配置文件
<configuration>
<connectionStrings>
</connectionStrings>
//下面三行是添加的内容,即连接数据库的信息
<appSettings>
<add key="connect" value="server=.;database=NorthWind;uid=sa;pwd=sa;"/>
</appSettings>
<system.web>
//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);