[传智播客学习日记]ADO.Net连接与增删改查

今天学习基本的ADO,就是通过C#程序代码来操控数据库,其实说白了还是一堆函数,程序可越来越有英语课的感觉了。

为了省事,不写try什么的了。首先是最基本的登录和断开连接:

 1 #region 登陆数据库
2 //创建一个连接对象
3 SqlConnection con = new SqlConnection();
4
5 //连接字符串(可以在左边服务器资源管理器里自动生成):
6 //Data source=服务器名(IP地址)\实例名;
7 //Initial Catalog=数据库名;
8 //Integrated Security=True 集成身份验证
9 //User ID=xxx;Password=xxx 用户名密码登陆
10 string constr = @"Data source=IT-129\SQLEXPRESS;Initial Catalog=ItCastCn;Integrated Security=True";
11
12 //让字符串和SqlConnection对象关联
13 con.ConnectionString = constr;
14
15 //打开连接(避免重复打开)
16 if (con.State == System.Data.ConnectionState.Closed)
17 {
18 con.Open();
19 }
20 #endregion
21
22 #region 关闭数据库
23 //关闭连接
24 con.Close();
25
26 //释放非托管资源
27 con.Dispose();
28 #endregion

增删改都要使用SqlCommand的ExecuteNonQuery方法,下面这个例子从窗体中读取用户输入,并且修改数据库:

 1 private void button1_Click(object sender, EventArgs e)
2 {
3 //从控件中取得字符串
4 string autoId = txt_autoId.Text.Trim();
5 string BrandName = txt_BrandName.Text.Trim();
6 string Price = txt_Price.Text.Trim();
7
8 //建立连接字符串
9 string constr = @"Data source=IT-129\SQLEXPRESS;Initial Catalog=ItCastCn;Integrated Security=True";
10
11 //新建一个SqlConnection对象con对数据库进行控制(连接器)
12 using (SqlConnection con = new SqlConnection(constr))
13 {
14 //定义SQL语句
15 string sql = string.Format
16 (
17 "update T1 " +
18 "set BrandName='{0}', price={1} " +
19 "where autoId = {2}" ,
20 BrandName, Price, autoId
21 );
22
23 //定义一个SqlCommand对象cmd(操作器),参数是SQL语句和连接器
24 using (SqlCommand cmd = new SqlCommand(sql, con))
25 {
26 //Open操作尽量晚
27 if (con.State == System.Data.ConnectionState.Closed)
28 {
29 con.Open();
30 }
31 //执行SQL语句,返回影响了几条
32 int r = cmd.ExecuteNonQuery();
33
34 //Close操作尽量早
35 con.Close();
36 MessageBox.Show("已成功修改" + r + "条语句!");
37 }
38 }
39 }

使用SqlDataReader输出整个表,假设一个表里有3列:

 1 using (SqlConnection con = new SqlConnection(constr))
2 {
3 string sql = "select * from dbo.ClassInfo";
4
5 using (SqlCommand cmd = new SqlCommand(sql, con))
6 {
7 if (con.State == System.Data.ConnectionState.Closed)
8 {
9 con.Open();
10 }
11
12 //这句话执行后并没有返回,存放在服务器的内存里
13 SqlDataReader reader = cmd.ExecuteReader();
14 using (reader)
15 {
16 if (reader.HasRows)
17 {
18 //读取每一行
19 while (reader.Read())
20 {
21 //读取每一列
22 //object obj1 = reader.GetValue(0);
23 //object obj2 = reader.GetValue(1);
24 //object obj3 = reader.GetValue(2);
25
26 //下标方式,可以根据列名取数据
27 //object obj1 = reader["ClassId"];
28 //object obj2 = reader[1];
29 //object obj3 = reader[2];
30
31 //建议使用这种强类型的方式提高性能
32 int obj1 = reader.GetInt32(0);
33 string obj2 = reader.GetString(1);
34 string obj3 = reader.GetString(2);
35
36 Console.WriteLine("{0}\t|\t{1}\t|\t{2}", obj1, obj2, obj3);
37 }
38 }
39 else
40 {
41 Console.WriteLine("x");
42 }
43 }
44
45 con.Close();
46 }
47 }

如果在一条SQL语句当中有变量(以@开头),则可以这样:

1 cmd.Parameters.AddWithValue("@SQL变量名",值);




原文地址:https://www.cnblogs.com/Elijah/p/2236612.html