C# 插入数据写回数据库,InsertCommand的使用方法

       实例的基本代码如下:by yl 2008.5.22 有任何问题联系:[email protected]

       OleDbDataAdapter Adpt;

        //临时表名

        string tempTableName = "NewTable";

        //返回数据DataSet数据集

        public DataSet Db_CreateDataSet(string SQL)

        {

            try

            {

                cmd = new OleDbCommand(SQL, Conn );

                Adpt = new OleDbDataAdapter(cmd);

 

 

                DataSet Ds = new DataSet();

                Adpt.Fill(Ds, tempTableName);

                return Ds;

            }

            catch (Exception ex)

            {

                MessageBox.Show("错误:" + ex.Message + ",无法执行:" + SQL);

                return null;

            }

 

        }

    //如果成功返回空,否则返回insertsql

        public string  InsertDataSet(DataSet ds)

        {

 

            OleDbCommandBuilder commandBuilder = new OleDbCommandBuilder(Adpt);

            Adpt.InsertCommand = commandBuilder.GetInsertCommand();

            string insertSQL = Adpt.InsertCommand.CommandText;

           

           try

            {

 

                Adpt.Update(ds, tempTableName);

                return "";

            }

            catch

            {

                return insertSQL;

            }

 

        }

private void InsertData(string TableName)//插入一个表的数据

        {

            string sql = "select * from " + TableName;

 

            DataSet accessDataSet = Db_CreateDataSet(sql);

            DataTable accessDataTable = accessDataSet.Tables[0];

            int num =10;

            for (int i = 0; i < num; i++)

            {

                DataRow accessDataRow = accessDataTable.NewRow();

                for (int j = 0; j < accessDataTable.Columns.Count - 1; j++)

                {

                    accessDataRow[j] =  //更新数据

 

                }

                accessDataTable.Rows.Add(accessDataRow);

 

            }

           InsertDataSet(accessDataSet);

 

你可能感兴趣的:(sql,exception,数据库,String,C#,dataset)