用DataAdapter的Update操作Insert,Update

// 构造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;
            }
 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值