您的位置:首页 > 编程语言 > C#

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

2009-04-28 09:47 369 查看
经常用到所以记录下来,免得找找麻烦 ヘ(-_-ヘ フフフフフ

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

具体就不介绍了,同道中人,不点亦明。

关于config文件中DB链接的存储方法,参考这里

/article/6991561.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();

}

}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐