1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
我自己写的一个简单的类。你自己调用它的相应函数来执行各种操作吧。
把constr改成你自己的。
public static class SqlHelper
{
public static string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
///
///
///
/// 要执行的sql操作语句,返回首行首列的值
///
public static int ExcuteScalar(string sql)
{
using (SqlConnection con =new SqlConnection(constr))
{
con.Open();
using (SqlCommand cmd=new SqlCommand(sql,con))
{
int r = 0;
if (cmd.ExecuteScalar()!=null)
{
r = (int)cmd.ExecuteScalar();
}
return r;
}
}
}
///
/// 执行查询,返回一个DataTable对象
///
/// 要执行的查询语句
///
public static DataTable ExctuteDataTable(string sql)
{
using (SqlConnection con=new SqlConnection(constr))
{
con.Open();
using (SqlDataAdapter sda=new SqlDataAdapter(sql,con))
{
DataTable dt = new DataTable();
sda.Fill(dt);
return dt;
}
}
}
///
/// 执行查询,返回一个SQLDataReader对象
///
/// 连接的数据库字符串
/// 执行的sql语句
/// 所要执行的参数化查询时,参数的值
///
/*返回SQLDataReader时,Connection和SQLCommand都不能关闭,关闭了的话返回的DataReader就没有任何数据了
解决这个问题:调用ExecuteReader()时传入一个 叫 CommandBehavior的参数,
表示用户关闭DataReader时、Connection和Command也自动被关闭。
*/
public static SqlDataReader ExecuteDataReader(string sql, SqlParameter[] pms)
{
SqlConnection con = new SqlConnection(constr);
con.Open();
SqlCommand cmd = new SqlCommand(sql, con);
if (pms != null)
{
cmd.Parameters.AddRange(pms);
}
//CommandBehavior.CloseConnection这个参数表示当DataReader关闭时,Connection、Command也被自动关闭
SqlDataReader reader = cmd.ExecuteReader(CommandBehavior.CloseConnection);
return reader;
}
///
/// 通过SqlCommand执行增删改操作
///
/// 要执行的操作语句
///
public static int ExecuteNonQuery(string sql)
{
using (SqlConnection con = new SqlConnection(constr))
{
con.Open();
using (SqlCommand cmd = new SqlCommand(sql, con))//Command类执行增删改
{
int count = 0;
count = cmd.ExecuteNonQuery();
return count;
}
}
}
}
我能帮助楼主完成这个任务,有现成的。