使用SqlDataAdapter来插入数据   

string _strConn = "Data Source=127.0.0.1;Initial Catalog=community;Persist Security Info=True;User ID=sa;Password=sa";
            SqlConnection _conn = new SqlConnection();
            _conn.ConnectionString = _strConn;
            _conn.Open();

            SqlCommand _cmd = new SqlCommand();
            _cmd.Connection = _conn;
            _cmd.CommandText = "select name,kecheng,fenshu from test where 1=0";
            SqlDataAdapter _adapter = new SqlDataAdapter();
            SqlCommandBuilder _build = new SqlCommandBuilder(_adapter);
            _adapter.SelectCommand = _cmd;
            _adapter.InsertCommand = new SqlCommand("insert into test(name,kecheng,fenshu)values(@name,@kecheng,@fenshu)",_conn);
            SqlParameter _parameter = null;
            _parameter =  _adapter.InsertCommand.Parameters.Add("@name", SqlDbType.VarChar, 10);
            _parameter.SourceColumn = "name";
            _parameter.SourceVersion = DataRowVersion.Original;
            _parameter = _adapter.InsertCommand.Parameters.Add("@kecheng", SqlDbType.VarChar, 10);
            _parameter.SourceColumn = "kecheng";
            _parameter.SourceVersion = DataRowVersion.Original;
            _parameter = _adapter.InsertCommand.Parameters.Add("@fenshu", SqlDbType.Int);
            _parameter.SourceColumn = "fenshu";
            _parameter.SourceVersion = DataRowVersion.Original;

            _adapter.InsertCommand = _build.GetInsertCommand();

            DataSet _ds = new DataSet();
           
            _adapter.Fill(_ds,"test");
            DataRow _row = _ds.Tables[0].NewRow();
            _row[0] = "lins";
            _row[1] = "物理";
            _row[2] = 99;
            _ds.Tables[0].Rows.Add(_row);
            int _n = _adapter.Update(_ds,"test");
            Console.WriteLine(_n);
            _ds.Clear();
            _conn.Close();
            _adapter.Dispose();

posted on 2008-11-03 21:25  Dot-Boy  阅读(594)  评论(0编辑  收藏  举报