C#的基本DB操作之【插入】

常用到所以记录下来,免得找找麻 ヘ(-_-ヘ フフフフフ

 

瞎编了个数据库和表,反正可以编译通过,呵呵~

具体就不介绍了,同道中人,不点亦明。
关于config文件中DB链接的存储方法,参考这里
http://www.cnblogs.com/Kenr/archive/2009/04/27/1444610.html

       

        /// <summary>

        /// 示例代write by 阿米巴原虫~)

        /// </summary>

        /// <param name="studentID">学生号</param>

        /// <param name="studentName">学生姓名</param>

        private void DBInsert(string studentID, string studentName)

        {

            SqlConnection connection = null;

            SqlCommand command = null;

            //建立一个程,当插入失候可以回

            SqlTransaction transaction = null;

            try

            {

                string commText = string.Empty;

                //config文件内的DB接字符串

                connection = new SqlConnection(ConfigurationManager.AppSettings["DB.ConnectionString"]);               

                connection.Open();

                command = connection.CreateCommand();

                transaction = connection.BeginTransaction();

                command.Transaction = transaction;

                commText += "insert into <DBName>.<schema>.<TableName>";

                commText += "(student_id,student_name,last_update)";

                commText += "select @studentID,@studentName,@lastUpdate";

                command.CommandText = commText;

                command.Parameters.Add(new SqlParameter("@studentID", "<字段1>"));

                command.Parameters.Add(new SqlParameter("@studentName", "<字段2>"));

                command.Parameters.Add(new SqlParameter("@lastUpdate", System.DateTime.Now.ToString()));

                //返回插入的行数

                int insertCount = command.ExecuteNonQuery();

                transaction.Commit();

            }

            catch (Exception e)

            {

                //错误则

                if (transaction != null)

                {

                    transaction.Rollback();

                }

                //错误抛向上一

                throw e;

            }

            //最后万万不能忘的,关闭连

            finally

            {

                if (connection != null)

                {

                    connection.Close();

                }

            }

        }

posted on 2009-04-28 09:47  阿米巴原虫  阅读(525)  评论(0编辑  收藏  举报