黑马程序员技术交流社区
标题: C#数据库连接 [打印本页]
作者: 熊丽 时间: 2013-8-1 23:24
标题: C#数据库连接
用SqlDataAdapter+DataSet
SqlConnection con = new SqlConnection();
con.ConnectionString ="server=(local);uid=sa;pwd=sa;database=Northwind;";
SqlCommand cmd = new SqlCommand();
cmd.CommandText = "select * from Employees";
cmd.Connection = con;
SqlDataAdapter sda = new SqlDataAdapter();
sda.SelectCommand = cmd;
con.Open();//打开数据库连接
DataSet ds = new DataSet();
sda.Fill(ds, "Employees");//用Employees表填充数据集
con.Close();//关闭数据库连接
this.GridView1.DataSource = ds;
this.GridView1.DataBind();
用SqlDataReader
SqlConnection con = new SqlConnection
ConnectionString ="server=(local);uid=sa;pwd=sa;database=Northwind;";
SqlCommand cmd = new SqlCommand();
cmd.CommandText = "select * from Employees";
cmd.Connection = con;
con.Open();//打开数据库连接
SqlDataReader sdr = cmd.ExecuteReader();
this.GridView1.DataSource = sdr;
this.GridView1.DataBind();//将数据绑定到GridView控件中
con.Close();//关闭数据库连接
作者: 许庭洲 时间: 2013-8-2 06:23
值得学习ing!
作者: 熊丽 时间: 2013-8-2 10:55
呵呵O(∩_∩)O~
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/) |
黑马程序员IT技术论坛 X3.2 |