.net是如何连接SQL数据库的?

.net是如何连接SQL数据库的?


HUX布斯
浏览 528回答 2
2回答

胡说叔叔

在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();}}

守着星空守着你

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();
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

SQL Server