2 回答

TA貢獻(xiàn)1815條經(jīng)驗(yàn) 獲得超6個贊
在web.config文件中的<appSettings>節(jié)點(diǎn)下,添加如下內(nèi)容:
<add key="ConnKey" value="Data Source=KO\MSSQLSERVER005;Initial Catalog=Web; User Id=sa;Password=sa;" />
下面是數(shù)據(jù)庫連接文件,先定義公共變量SqlConn和ConnKeyStr ,請注意引號內(nèi)“ConnKey”與web.config設(shè)定值需一致。
public SqlConnection SqlConn;
public static string ConnKeyStr = ConfigurationManager.AppSettings["ConnKey"].ToString();
下面兩個函數(shù),一個是打開數(shù)據(jù)連接,另一個是關(guān)閉數(shù)據(jù)連接。
//打開連接
public void SqlConnOpen()
{
if (SqlConn == null)
{
SqlConn = new SqlConnection(ConnKeyStr);
if (SqlConn.State != ConnectionState.Open)
{
try
{
SqlConn.Open();
}
catch
{
throw new Exception("打開數(shù)據(jù)庫失??!");
}
}
}
else if(SqlConn.State!=ConnectionState.Open)
{
try
{
SqlConn.Open();
}
catch
{
throw new Exception("打開數(shù)據(jù)庫失敗!");
}
}
}
//關(guān)閉連接
public void SqlConnClose()
{
if (SqlConn.State != ConnectionState.Closed)
{
SqlConn.Close();
}
}

TA貢獻(xiàn)1820條經(jīng)驗(yàn) 獲得超9個贊
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 關(guān)注
- 623 瀏覽
添加回答
舉報