用DataAdapter的Update操作Insert,Update

时间:2023-01-08 10:18:17
//构造DataTable
            DataTable dt=new DataTable("demo");
            dt.Columns.Add("pkid",typeof(System.Int32)).Caption="序号";
            dt.Columns.Add("user_name", typeof(System.String)).Caption="用户名";
            dt.Columns.Add("passwd",typeof(System.String)).Caption="密码";

            //填充DataTable
            DataRow dr=dt.NewRow();
            dr["pkid"]=0;
            dr["user_name"]=this.txtName.Text;
            dr["passwd"]=this.txtPasswd.Text;
            dt.Rows.Add(dr);
        
            //构造DataSet
            DataSet ds=new DataSet();
            //填充DataSet
            ds.Tables.Add(dt);

            string strConn="Provider=SQLOLEDB;Data Source=localhost;Initial Catalog=myweb;user id=sa;";
            try
            {
                OleDbConnection conn = new OleDbConnection(strConn);

                //参数在OleDbCommand或ODBCCommand中用?,SqlCommand中用@开头的参数,OracleCommand中的用:开头的参数
                OleDbCommand comm=new OleDbCommand(@"insert into demo(user_name,passwd) values(?,?) ",conn);
                comm.Parameters.Add("@user_name",OleDbType.VarChar,50,"user_name");
                comm.Parameters.Add("@passwd",OleDbType.VarChar,50,"passwd");
    
                OleDbDataAdapter da = new OleDbDataAdapter();
                //DataAdapter中的DataTable与数据库中的表建立映射
                da.TableMappings.Add("demo","demo");
                //设置InsertCommand
                da.InsertCommand=comm;
                //更新表
                da.Update(ds,"demo");
                //刷新
                ds.AcceptChanges();

                MessageBox.Show("Iniseted Success!");

                comm.Dispose();
                conn.Close();
                conn.Dispose();
            }
            catch(Exception ex)
            {
                string err=ex.Message;
            }