连接本地SQL Server数据库学习示例。
1,配置web.config。
1 <connectionStrings> 2 <add name="We7_CMS" connectionString="Data Source=ZhangNan-PC; Initial Catalog=We7_CMS ; Integrated Security=SSPI"/> 3 </connectionStrings>
2,写一个测试连接的web form
1 <body> 2 <form id="form1" runat="server"> 3 <div> 4 <asp:Label runat="server" ID="lblInfo"></asp:Label> 5 </div> 6 </form> 7 </body>
1 protected void Page_Load(object sender, EventArgs e) 2 { 3 string connectionString = WebConfigurationManager.ConnectionStrings["We7_CMS"].ConnectionString; 4 SqlConnection con = new SqlConnection(connectionString); 5 6 try 7 { 8 con.Open(); 9 lblInfo.Text = "<b>Version : </b>"+con.ServerVersion; 10 lblInfo.Text += "<br /><b>Connection Is:</b>" + con.State.ToString(); 11 } 12 catch (Exception err) 13 { 14 lblInfo.Text = "Error reading the database." + err.Message; 15 } 16 finally 17 { 18 con.Close(); 19 lblInfo.Text += "<br /><b> Now Connection Is : </b>" + con.State.ToString(); 20 } 21 22 23 }
测试结果如下:
Version : 10.00.1600
Connection Is:Open
Now Connection Is : Closed