2 回答
TA贡献1804条经验 获得超8个赞
在web.config文件中的<appSettings>节点下,添加如下内容:
<add key="ConnKey" value="Data Source=KO\MSSQLSERVER005;Initial Catalog=Web; User Id=sa;Password=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();
}
}
TA贡献1799条经验 获得超8个赞
using System.Data.SqlClient;
SqlConnection cn = new SqlConnection("data source=(local);initial catalog=database_breakfast;user=sa;pwd=");
SqlCommand cmd = new SqlCommand(" select * from t_product_sort ", cn);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds, "prosort");
this.GridView1.DataSource = ds.Tables[0].DefaultView;
this.DataBind();
- 2 回答
- 0 关注
- 527 浏览
添加回答
举报