C#连接sql server2005数据库

来源:互联网 发布:中国对外工程承包数据 编辑:程序博客网 时间:2024/05/21 10:00
网上关于C#连接sal server2005的资料不多,也不全面,对于一个初学者来说要花很长时间看懂。本人经过查找资料和自己的总结,来分享下成果:
using System;using System.Collections.Generic;using System.Linq;using System.Web;using System.Web.UI;using System.Web.UI.WebControls;using System.Data.SqlClient;namespace WebTest2.webRoot{    public partial class JDBC : System.Web.UI.Page    {        protected void Page_Load(object sender, EventArgs e)        {            //建立数据库连接字符串            string connectionString = "server=localhost;database=test;uid=sa;pwd=123";            //将连接字符串传入SqlConnection对象的构造函数中            SqlConnection mySqlConnection = new SqlConnection(connectionString);            try            {                //打开连接                mySqlConnection.Open();                //利用label控件显示mySqlConnection对象的ConnectionString属性                lblInfo.Text = "mySqlConnection对象的ConnectionString属性为:" +                mySqlConnection.ConnectionString;                lblInfo1.Text += "mySqlConnection对象的ConnectionTimeout属性为" +                mySqlConnection.ConnectionTimeout;                lblInfo2.Text += "mySqlConnection对象的Database属性为" +                mySqlConnection.Database;                lblInfo3.Text += "mySqlConnection对象的DataSource属性为" +                mySqlConnection.DataSource;                lblInfo4.Text += "mySqlConnection对象的PacketSize属性为" +                mySqlConnection.PacketSize;                lblInfo5.Text += "mySqlConnection对象的ServerVersion属性为" +                mySqlConnection.ServerVersion;                lblInfo6.Text += "mySqlConnection对象的当前状态为" +                mySqlConnection.State;            }            catch (Exception err)            {                lblInfo7.Text = "读取数据库出错";                lblInfo8.Text += err.Message;            }            finally            {                //关闭与数据库的连接                mySqlConnection.Close();                lblInfo9.Text += "关闭连接后的mySqlConnection对象的状态为";                lblInfo10.Text += mySqlConnection.State.ToString();            }        }    }}


注意:如果你的开发工具中没有提示SqlConnection,你需要引入using System.Data.SqlClient;下面教你如何创建出代码中的类:

会生出成三个文件
上面代码在JDBC.aspx.cs中写。
lblInfo.Text 调用的是JDBC.aspx的textBox中的id属性,<asp:textBox></asp:textBox>可以在视图的工具箱拖控件!

 

原创粉丝点击