-
Notifications
You must be signed in to change notification settings - Fork 0
/
SQLHelper.cs
104 lines (91 loc) · 2.34 KB
/
SQLHelper.cs
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
95
96
97
98
99
100
101
102
103
104
using System;
using System.Data;
using System.Data.SqlClient;
namespace SQLGenerator
{
public class SQLHelper
{
public string ConnectionString { set; get; }
public SqlConnection SqlConnection;
public SQLHelper(string conString)
{
ConnectionString = conString;
}
//连接数据库
public void OpenDB()
{
if (SqlConnection == null)
SqlConnection = new SqlConnection(ConnectionString);
if (SqlConnection.State == ConnectionState.Open)
SqlConnection.Close();
SqlConnection.Open();
}
//关闭数据库
public void CloseDB()
{
try
{
SqlConnection.Close();
}
catch { }
}
public int ExecuteSQL(String sql)
{
//int cmd = 0;
try
{
OpenDB();
SqlCommand cmm = new SqlCommand(sql, SqlConnection);
int cmd = cmm.ExecuteNonQuery();
CloseDB();
return cmd;
}
catch (Exception e)
{
throw e;
}
}
//执行Select,返回DataReader
public SqlDataReader GetDataReader(String sql)
{
try
{
SqlDataReader dr;
OpenDB();
SqlCommand cmm = new SqlCommand(sql, SqlConnection);
dr = cmm.ExecuteReader();
//CloseDB();
return dr;
}
catch (Exception e)
{
throw e;
}
finally
{
CloseDB();
}
}
//获取DataTable
public DataTable GetDataTable(string CmdString)
{
try
{
OpenDB();
SqlDataAdapter myDa = new SqlDataAdapter();
myDa.SelectCommand = new SqlCommand(CmdString, SqlConnection);
DataTable myDt = new DataTable();
myDa.Fill(myDt);
return myDt;
}
catch (Exception e)
{
throw e;
}
finally
{
CloseDB();
}
}
}
}