然后在Webform_ aspx cs里面获取连接字符串 要添加如下引用
复制代码 代码如下: using System Configurationusing System Datausing System Data SqlClient 复制代码 代码如下: SqlConnection conprotected void Page_Load(object sender EventArgs e) { ConnectDB()} private void ConnectDB() { string ConString = ConfigurationManager ConnectionStrings["ConnectionString"] ConnectionStringcon = new SqlConnection(ConString)con Open()SqlCommand = new SqlCommand()SqlDataReader sdrstring sqlstr = "select * from item"CommandText = sqlstrConnection = consdr = ExecuteReader()while (sdr Read()) { Response Write(sdr["字段名"] ToString()+"</br>")} sdr Close()sdr = null} lishixinzhi/Article/program/net/201311/14106在web.config文件中的<appSettings>节点下,添加如下内容:
<add key="ConnKey" value="Data Source=KO\MSSQLSERVER005Initial Catalog=WebUser Id=saPassword=sa" />
下面是数据库连接文件,先定义公共变量SqlConn和ConnKeyStr ,请注意引号内“ConnKey”与web.config设定值需一致。
public SqlConnection SqlConn
public static string ConnKeyStr = ConfigurationManager.AppSettings["ConnKey"].ToString()
下面两个函数,一个是打开数据连接,另一个是关闭数据连接。
//打开连接
public void SqlConnOpen()
{
if (SqlConn == null)
{
SqlConn = new SqlConnection(ConnKeyStr)
if (SqlConn.State != ConnectionState.Open)
{
try
{
SqlConn.Open()
}
catch
{
throw new Exception("打开数据库失败!")
}
}
}
else if(SqlConn.State!=ConnectionState.Open)
{
try
{
SqlConn.Open()
}
catch
{
throw new Exception("打开数据库失败!")
}
}
}
//关闭连接
public void SqlConnClose()
{
if (SqlConn.State != ConnectionState.Closed)
{
SqlConn.Close()
}
}
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)