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

关于 通过SqlDataAdapter 插入DataSet中的数据到数据库 有两种方法:

(1)

使用SqlCommandBuilder

  SqlConnection conn=new SqlConnection();
            conn.ConnectionString=ConfigurationManager.ConnectionStrings["TestDBConnectionString"].ConnectionString;
            conn.Open();
            SqlCommand cmd=new SqlCommand();
            cmd.CommandText="select * from UserInfo";
            cmd.CommandType=CommandType.Text;
            cmd.Connection=conn;
            SqlDataAdapter adapter = new SqlDataAdapter();
            SqlCommandBuilder build = new SqlCommandBuilder(adapter);
            DataSet ds = new DataSet();
            adapter.SelectCommand = cmd;
            adapter.Fill(ds);
            DataRow row = ds.Tables[0].NewRow();
            row["UserName"] = "lhhhhhhhhhhhh";
            row["UserSex"] = 0;
            ds.Tables[0].Rows.Add(row);      
            adapter.Update(ds);
            adapter.Dispose();
            cmd.Dispose();
            conn.Dispose();

(2) 使用 sqldataadapter 中的 insertcommand:

       SqlConnection conn=new SqlConnection();
            conn.ConnectionString=ConfigurationManager.ConnectionStrings["TestDBConnectionString"].ConnectionString;
            conn.Open();
            SqlCommand cmd=new SqlCommand();
            cmd.CommandText="select * from UserInfo";
            cmd.CommandType=CommandType.Text;
            cmd.Connection=conn;
            SqlDataAdapter adapter = new SqlDataAdapter();
            DataSet ds = new DataSet();
            adapter.SelectCommand = cmd;
            adapter.Fill(ds);
            DataRow row = ds.Tables[0].NewRow();
            row["UserName"] = "ccccjjjjjjjjjjj";
            row["UserSex"] = 0;
            ds.Tables[0].Rows.Add(row);
            cmd.CommandText = "insert into UserInfo values(@username,@usersex)";
            adapter.InsertCommand=cmd;
            cmd.Parameters.Add(new SqlParameter("@username",SqlDbType.VarChar,50));
            cmd.Parameters.Add(new SqlParameter("@usersex", SqlDbType.Bit));
            cmd.Parameters[0].SourceColumn = "UserName";
            cmd.Parameters[0].SourceVersion = DataRowVersion.Original;
            cmd.Parameters[1].SourceColumn = "UserSex";
            cmd.Parameters[1].SourceVersion = DataRowVersion.Original;
            adapter.Update(ds);
            adapter.Dispose();
            cmd.Dispose();
            conn.Dispose();
 


你可能感兴趣的:(Adapter)