通过SqlDataAdapter 插入DataSet中的数据到数据库

 1 关于 通过SqlDataAdapter 插入DataSet中的数据到数据库 有两种方法:
2
3 (1)
4
5 使用SqlCommandBuilder
6
7 SqlConnection conn=new SqlConnection();
8 conn.ConnectionString=ConfigurationManager.ConnectionStrings["TestDBConnectionString"].ConnectionString;
9 conn.Open();
10 SqlCommand cmd=new SqlCommand();
11 cmd.CommandText="select * from UserInfo";
12 cmd.CommandType=CommandType.Text;
13 cmd.Connection=conn;
14 SqlDataAdapter adapter = new SqlDataAdapter();
15 SqlCommandBuilder build = new SqlCommandBuilder(adapter);
16 DataSet ds = new DataSet();
17 adapter.SelectCommand = cmd;
18 adapter.Fill(ds);
19 DataRow row = ds.Tables[0].NewRow();
20 row["UserName"] = "lhhhhhhhhhhhh";
21 row["UserSex"] = 0;
22 ds.Tables[0].Rows.Add(row);
23 adapter.Update(ds);
24 adapter.Dispose();
25 cmd.Dispose();
26 conn.Dispose();
27
28 (2) 使用 sqldataadapter 中的 insertcommand:
29
30 SqlConnection conn=new SqlConnection();
31 conn.ConnectionString=ConfigurationManager.ConnectionStrings["TestDBConnectionString"].ConnectionString;
32 conn.Open();
33 SqlCommand cmd=new SqlCommand();
34 cmd.CommandText="select * from UserInfo";
35 cmd.CommandType=CommandType.Text;
36 cmd.Connection=conn;
37 SqlDataAdapter adapter = new SqlDataAdapter();
38 DataSet ds = new DataSet();
39 adapter.SelectCommand = cmd;
40 adapter.Fill(ds);
41 DataRow row = ds.Tables[0].NewRow();
42 row["UserName"] = "ccccjjjjjjjjjjj";
43 row["UserSex"] = 0;
44 ds.Tables[0].Rows.Add(row);
45 cmd.CommandText = "insert into UserInfo values(@username,@usersex)";
46 adapter.InsertCommand=cmd;
47 cmd.Parameters.Add(new SqlParameter("@username",SqlDbType.VarChar,50));
48 cmd.Parameters.Add(new SqlParameter("@usersex", SqlDbType.Bit));
49 cmd.Parameters[0].SourceColumn = "UserName";
50 cmd.Parameters[0].SourceVersion = DataRowVersion.Original;
51 cmd.Parameters[1].SourceColumn = "UserSex";
52 cmd.Parameters[1].SourceVersion = DataRowVersion.Original;
53 adapter.Update(ds);
54 adapter.Dispose();
55 cmd.Dispose();
56 conn.Dispose();
57

你可能感兴趣的:(通过SqlDataAdapter 插入DataSet中的数据到数据库)