日期:2014-05-16 浏览次数:20488 次
using System; using System.Collections.Generic; using System.Collections; using System.Collections.Specialized; using System.Runtime.Remoting.Messaging; using System.Data; using System.Data.SqlClient; using System.Configuration; using System.Text; public abstract class DBUtility { //数据库连接字符串 protected static string connectionstring = ConfigurationSettings.AppSettings["conStr"]; public static string conStr { get { return connectionstring; } } public DBUtility() { // // todo: 在此处添加构造函数逻辑 // } /// <summary> /// 执行sql语句,返回影响的记录数 /// </summary> /// <param name="sqlstring"></param> /// <returns></returns> public static int ExecuteSql(string sqlString) { using ( SqlConnection connection = new SqlConnection(connectionstring)) { using (SqlCommand cmd = new SqlCommand(sqlString, connection)) { try { connection.Open(); int rows=cmd.ExecuteNonQuery(); return rows; } catch(System.Data.SqlClient.SqlException e) { throw new Exception(e.Message); } } } } /// <summary> /// 执行两条sql语句,实现数据库事务。 /// </summary> /// <param name="sqlstring1"></param> /// <param name="sqlstring2"></param> public static void ExecuteSqlTran(string sqlstring1,string sqlstring2) { using (SqlConnection connection = new SqlConnection(connectionstring)) { connection.Open(); SqlCommand cmd = new SqlCommand(); cmd.Connection=connection; SqlTransaction tx=connection.BeginTransaction(); cmd.Transaction=tx; try { cmd.CommandText=sqlstring1; cmd.ExecuteNonQuery(); cmd.CommandText=sqlstring2; cmd.ExecuteNonQuery(); tx.Commit(); } catch(System.Data.SqlClient.SqlException e) { tx.Rollback(); throw new Exception(e.Message); } finally { cmd.Dispose(); connection.Close(); } } } /// <summary> /// 执行多条sql语句,实现数据库事务,每条语句以“;”分割。 /// </summary> /// <param name="sqlstringlist"></param> public static void ExecuteSqlTran(string sqlstringlist) { using (SqlConnection conn = new SqlConnection(connectionstring)) { conn.Open(); SqlCommand cmd = new SqlCommand(); cmd.Connection=conn; SqlTransaction tr =conn.BeginTransaction(); cmd.Transaction=tr; try { string [] split= sqlstringlist.Split(new char [] {';'}); foreach (string strsql in split) { if (strsql.Trim()!="") { cmd.CommandText=strsql; cmd.ExecuteNonQuery(); } } tr.Commit(); } catch(System.Data.SqlClient.SqlException e) { tr.Rollback(); throw new Exception(e.Message); } } } /// <summary> /// 向数据库里插入图像格式的字段 /// </summary> /// <param name="strsql"></param> /// <param name="fs"></param> /// <returns></returns> public static int ExecuteSqlInsertImg(string strsql,byte[] fs) { using (SqlConnection connection = new SqlConnection(connectionstring)) { SqlCommand cmd = new SqlCommand(strsql,connection); System.Data.SqlClient.SqlParameter myparameter = new System.Data.SqlClient.SqlParameter ( "@fs", SqlDbType.Image); myparameter.Value = fs ; cmd.Parameters.Add(myparameter); try { connection.Open(); int rows=cmd.ExecuteNonQuery(); return rows; } catch(System.Data.SqlClient.SqlException e) { throw new Exception(e.Message); } finally {