1 using System; 2 using System.Collections.Generic; 3 using System.Configuration; 4 using System.Data.SqlClient; 5 using System.Linq; 6 using System.Text; 7 using System.Threading.Tasks; 8 using System.Data; 9 10 namespace Students.DAL 11 { 12 public class DBHelper 13 { 14 public static readonly string conn = ConfigurationManager.ConnectionStrings["ClassRoomConnectionString"].ToString(); 15 public static SqlConnection connection = new SqlConnection(DBHelper.conn); 16 17 ///18 /// 增删改数据 19 /// 20 /// 21 ///22 public static int ExecuteNonQuery(string sql, SqlParameter[] par) 23 { 24 try 25 { 26 connection.Open(); //打开数据库连接 27 SqlCommand comm = new SqlCommand(sql, connection); 28 //comm.CommandType = System.Data.CommandType.StoredProcedure; 29 comm.Parameters.AddRange(par); 30 return comm.ExecuteNonQuery(); 31 } 32 catch 33 { 34 throw; 35 } 36 finally 37 { 38 connection.Close(); 39 } 40 } 41 /// 42 /// 增删改数据 43 /// 44 /// 45 ///46 public static int ExecuteNonQuery(string sql, SqlParameter[] par, string sql2, SqlParameter[] par2) 47 { 48 connection.Open(); //打开数据库连接 49 SqlTransaction tra = connection.BeginTransaction(); 50 try 51 { 52 SqlCommand comm = new SqlCommand(sql, connection); 53 SqlCommand comm2 = new SqlCommand(sql2, connection); 54 comm.Parameters.AddRange(par); 55 comm2.Parameters.AddRange(par2); 56 comm.Transaction = tra; 57 comm2.Transaction = tra; 58 int num1 = comm.ExecuteNonQuery(); 59 int num2 = comm2.ExecuteNonQuery(); 60 int num = comm.ExecuteNonQuery() + comm2.ExecuteNonQuery(); 61 tra.Commit(); 62 return num; 63 } 64 catch 65 { 66 tra.Rollback(); 67 throw; 68 } 69 finally 70 { 71 connection.Close(); 72 } 73 } 74 /// 75 /// 查询数据 76 /// 77 /// 78 ///79 public static SqlDataReader ExecuteReader(string sql, SqlParameter[] par) 80 { 81 try 82 { 83 connection.Open(); //打开数据库连接 84 SqlCommand comm = new SqlCommand(sql, connection); 85 //comm.CommandType = System.Data.CommandType.StoredProcedure; 86 comm.Parameters.AddRange(par); 87 return comm.ExecuteReader(CommandBehavior.CloseConnection); 88 } 89 catch 90 { 91 throw; 92 } 93 } 94 /// 95 /// 查询数据 96 /// 97 /// 98 ///99 public static SqlDataReader ExecuteReader(string sql)100 {101 try102 {103 connection.Open(); //打开数据库连接104 SqlCommand comm = new SqlCommand(sql, connection);105 return comm.ExecuteReader(CommandBehavior.CloseConnection);106 }107 catch108 {109 throw;110 }111 }112 /// 113 /// 返回单个值114 /// 115 /// 116 ///117 public static object ExecuteScalar(string sql, SqlParameter[] par)118 {119 try120 {121 connection.Open(); //打开数据库连接122 SqlCommand comm = new SqlCommand(sql, connection);123 //comm.CommandType = System.Data.CommandType.StoredProcedure;124 comm.Parameters.AddRange(par);125 return comm.ExecuteScalar();126 }127 catch128 {129 throw;130 }131 finally132 {133 connection.Close();134 }135 }136 }137 }
然后再App.config文件中写连接语句
1 23 4 65 7 1110