1 //数据查询 DT-PC\\SQLEXPRESS
2 public static DataTable MyQuery(string str)
3 {
4 SqlConnection conn = new SqlConnection("data source=.; database=LJC0125_web; Integrated Security=SSPI");
5 conn.Open();
6 SqlDataAdapter da = new SqlDataAdapter(str, conn);
7 DataTable dt = new DataTable();
8 da.Fill(dt);
9 conn.Close();
10 return dt;
11 }
12 //数据操作
13 public static int MyExcute(string str)
14 {
15 SqlConnection conn = new SqlConnection("data source=.; database=LJC0125_web; Integrated Security=SSPI");
16 conn.Open();
17 //创建执行对象
18 SqlCommand cmd = new SqlCommand(str, conn);
19 //3.执行操作,返回受影响的行数
20 int i = cmd.ExecuteNonQuery();
21 //关闭连接
22 conn.Close();
23 //返回受影响行数
24 return i;
25 }
1 //对表的操作
2 private void Form3_Load(object sender, EventArgs e)
3 {
4 //在数据集中添加表
5 DataTable tbl = new DataTable("user");
6 ds.Tables.Add(tbl);
7
8 //定义表的列
9 DataColumn col = tbl.Columns.Add("id", typeof(Int32));
10 col.AutoIncrement = true;
11 col.AutoIncrementSeed = 0;
12 col.AutoIncrementStep = 1;
13 col.ReadOnly = true;
14
15 tbl.Columns.Add("name", typeof(String));
16 tbl.Columns.Add("birthday", typeof(DateTime));
17
18 //定义id列为表的主键
19 tbl.PrimaryKey = new DataColumn[] { tbl.Columns["id"] };
20
21 //添加三行相同的数据
22 for (int i = 0; i < 3; i++)
23 {
24 DataRow row = tbl.NewRow();
25 row[1] = "llx";
26 row[2] = DateTime.Now;
27 tbl.Rows.Add(row);
28 }
29
30 //显示到DataGridView控件中
31 dataGridView1.DataSource = ds.Tables["user"];
32
33
34 }
35
36 //添加一行
37 private void button1_Click(object sender, EventArgs e)
38 {
39 DataTable tbl = ds.Tables["user"];
40 DataRow row = tbl.NewRow();
41 row[1] = textBox1.Text;
42 row[2] = dateTimePicker1.Value;
43 tbl.Rows.Add(row);
44 }
45
46
47 //删除最后一行
48 private void button2_Click(object sender, EventArgs e)
49 {
50 DataTable tbl = ds.Tables["user"];
51 if (tbl.Rows.Count > 0)
52 {
53 DataRow row = tbl.Rows[tbl.Rows.Count - 1];
54 tbl.Rows.Remove(row);
55 }
56 }
57
58 //修改行
59 private void button3_Click(object sender, EventArgs e)
60 {
61 string s = "";
62
63 string s = ""
64
65 //查找特定行,进行修改
66 DataTable tbl = ds.Tables["user"];
67 DataRow row = tbl.Rows.Find(dataGridView1.CurrentRow.Cells[0].Value);
68
69 if (row != null)
70 {
71 s += "未修改前为:" + row[1].ToString();
72 if (textBox1.Text == "")
73 row[1] = DBNull.Value;
74 else
75 row[1] = textBox1.Text;
76 s += " 修改后为:" + row[1].ToString();
77 }
78
79 label1.Text = s;
80
81
82 }