黑马程序员_连接数据库

连接数据库
1.在配置文件中写
<connectionStrings>
    <add name="strConn" connectionString="Data Source=WANG-PC;Initial Catalog=WANG;User ID=sa;Password=123" />
  </connectionStrings>
然后在.aspx.cs中使用
string strconn = @System.Configuration.ConfigurationManager.ConnectionStrings["strConn"].ToString();
SqlConnection conn = new SqlConnection(strconn);

2.在.aspx.cs中直接用
SqlConnection conn = new SqlConnection("Data Source=WANG-PC;Initial Catalog=WANG;User ID=sa;Password=123");//连接数据库

3.断开式连接数据库:
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                databing();
            }
        }
        private void databing()
        {
            SqlConnection conn = new SqlConnection("Data Source=WANG-PC;Initial Catalog=WANG;User ID=sa;Password=123");//连接数据库
            conn.Open();//打开数据库
            SqlDataAdapter da = new SqlDataAdapter();//创建适配器 用于填充数据
            da.SelectCommand = new SqlCommand();//创建SQL命令
            da.SelectCommand.Connection = conn;//使用SQL命令连接数据库
            da.SelectCommand.CommandText ="select * from Student";//执行SQL
            da.SelectCommand.CommandType = CommandType.Text;//声明类型
            DataSet ds = new DataSet();//得到结果集
            da.Fill(ds, "CTable");//填充数据集
            conn.Close();//关闭数据库
            conn.Dispose();
            this.GridView1.DataSource = ds;
            this.GridView1.DataBind();
        }

4.连接式连接数据库:
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                databing();
            }
        }
        private void databing()
        {
            SqlConnection conn = new SqlConnection("Data Source=WANG-PC;Initial Catalog=WANG;User ID=sa;Password=123");//连接数据库
            conn.Open();//打开数据库
            SqlCommand smd = new SqlCommand();//创建SQL命令
            smd.Connection = conn;//使用SQL命令连接数据库
            smd.CommandText = "select * from Student";//执行SQL命令
            smd.CommandType = CommandType.Text;//声明类型
            SqlDataReader dr = smd.ExecuteReader();//创建阅读器
            while (dr.Read())//循环阅读数据
            {
                //Response.Write(dr["Name"] + "&nbsp" + dr["Sex"] + "&nbsp" + dr["Age"] + "&nbsp" + dr["School"] + "&nbsp" + dr["ByTime"]+"<br>");
                this.GridView1.DataSource = dr;
                this.GridView1.DataBind();
            }           
            conn.Close();
            conn.Dispose();
            dr.Close();
        }

 

 

posted @ 2013-04-16 18:36  微笑的小鸟  阅读(130)  评论(0编辑  收藏  举报