温馨提示:代码在线浏览功能只能做为源码浏览参考,如果想更进一步了解该代码请下载:选课系统(南昌大学毕业设计)及论文
当前文件:
XuankeDoc/Db.cs[3K,2009-6-12 12:00:17],打开代码结构图
XuankeDoc/Db.cs[3K,2009-6-12 12:00:17],打开代码结构图1using System; 2
using System.Data; 3
using System.Data.SqlClient; 4
using System.Configuration; 5
using System.Data.Common; 6
7
namespace sc 8
{ 9
/// <summary> 10
/// 数据库连接操作类 11
/// </summary> 12
public class Db 13
{ 14
/// <summary> 15
/// 数据库连接字符串 16
/// </summary> 17
protected static string connString = ConfigurationSettings.AppSettings["ConnectionString"]; 18
19
public Db() 20
{ 21
} 22
23
/// <summary> 24
/// 执行select类型的sql语句,返回select得到的数据集 25
/// </summary> 26
/// <param name="sqlSelect">select语句</param> 27
/// <returns>返回select得到的数据集</returns> 28
public static DataSet ExecuteSelectSql( string sqlSelect ) 29
{ 30
SqlConnection conn = new SqlConnection(connString); 31
SqlDataAdapter sda = new SqlDataAdapter(sqlSelect,conn); 32
DataSet ds = new DataSet(); 33
try 34
{ 35
sda.Fill(ds); 36
} 37
catch(SqlException e) 38
{ 39
throw new Exception(e.Message); 40
} 41
return ds; 42
} 43
44
/// <summary> 45
/// 执行insert,update,delete等语句,改变的行数 46
/// </summary> 47
/// <param name="sql">sql语句</param> 48
/// <returns>改变的行数</returns> 49
public static int ExecuteSql( string sql ) 50
{ 51
int rows = -1; 52
SqlConnection conn = new SqlConnection(connString); 53
SqlCommand cmd = new SqlCommand(sql,conn); 54
try 55
{ 56
conn.Open(); 57
rows = cmd.ExecuteNonQuery(); 58
} 59
catch(SqlException e) 60
{ 61
throw new Exception(e.Message); 62
} 63
finally 64
{ 65
cmd.Dispose(); 66
conn.Close(); 67
} 68
69
return rows; 70
} 71
72
/// <summary> 73
/// 执行需要返回刚插入记录的identity的insert语句,返回改变行数 74
/// </summary> 75
/// <param name="sqlInsert">insert语句</param> 76
/// <param name="identity">identity</param> 77
/// <returns>返回改变行数</returns> 78
public static int ExecuteInsertSql( string sqlInsert, ref int identity ) 79
{ 80
int rows = -1; 81
SqlConnection conn = new SqlConnection(connString); 82
SqlCommand cmd = new SqlCommand(); 83
84
try 85
{ 86
conn.Open(); 87
} 88
catch(SqlException e) 89
{ 90
throw new Exception(e.Message); 91
} 92
93
SqlTransaction trans = conn.BeginTransaction(); 94
try 95
{ 96
cmd.Connection = conn; 97
cmd.Transaction = trans; 98
//执行insert 99
cmd.CommandText = sqlInsert; 100
rows = cmd.ExecuteNonQuery(); 101
//select出identity 102
cmd.CommandText = "select @@identity"; 103
SqlDataReader sdr = cmd.ExecuteReader(); 104
if(sdr.Read()) 105
{ 106
identity = sdr.GetInt32(0); 107
} 108
109
trans.Commit(); 110
} 111
catch(System.Data.SqlClient.SqlException e) 112
{ 113
trans.Rollback(); 114
throw new Exception(e.Message); 115
} 116
finally 117
{ 118
cmd.Dispose(); 119
conn.Close(); 120
} 121
122
return rows; 123
} 124
125
} 126
} 127






}