#DBHelp
```
public class DBHelper
{
//数据库连接字符串
private static string connStr = "Data Source=.;Initial Catalog=stuDB;User ID=sa;Password=wdmm12315";
//数据库连接对象
public static SqlConnection conn = null;
/// <summary>
/// 建立数据连接方法,初始化数据库连接对象
/// </summary>
private static void InitConnection()
{
//初始化数据库连接对象
if (conn == null)
{
conn = new SqlConnection(connStr);
conn.Open();
}
//数据库连接对象损坏了
if (conn.State == ConnectionState.Broken)
{
conn.Close();
conn.Open();
}
//数据库连接对象关闭
if (conn.State == ConnectionState.Closed)
{
conn.Open();
}
}
public static SqlDataReader GetReader(string sql)
{
InitConnection();
SqlCommand cmd = new SqlCommand(sql, conn);
return cmd.ExecuteReader();
}
/// <summary>
/// 根据Sql命令,查询获取DataTable
/// </summary>
/// <param name="sql">sql命令字符串</param>
/// <returns>返回DataTable</returns>
public static DataTable GetDataTableBySql(string sql)
{
//创建数据表对象
DataTable dt = new DataTable();
try
{
//初始化数据库连接
InitConnection();
//创建SqlDataAdapter对象,负责将sql命令传给数据库,并执行
SqlDataAdapter dap = new SqlDataAdapter(sql, conn);
//dap填充DataTable
dap.Fill(dt);
}
catch (Exception)
{
dt = null;
throw;
}
finally
{
if (conn != null)
//关闭数据库连接对象
conn.Close();
}
//返回DataTable
return dt;
}
/// <summary>
/// 执行增、删、改
/// </summary>
/// <param name="sql">sql命令字符串</param>
/// <returns>若成功,返回true;否则,返回false</returns>
public static bool ExecuteNonQuery(string sql)
{
int result;
try
{
//初始化数据库连接
InitConnection();
//创建SqlCommand对象
SqlCommand cmd = new SqlCommand(sql, conn);
//执行sql命令,返回受影响的行数
result = cmd.ExecuteNonQuery();
}
catch (Exception)
{
result = 0;
throw;
}
finally
{
if (conn != null)
//关闭数据库连接对象
conn.Close();
}
//返回执行增、删、改结果
return result > 0;
}
public static DataTable GetDataTableByProc(string proc, SqlParameter[] paras)
{
DataTable dt = new DataTable();
try
{
InitConnection();
SqlCommand cmd = new SqlCommand(proc, conn);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddRange(paras);
SqlDataAdapter dap = new SqlDataAdapter(cmd);
dap.Fill(dt);
}
catch (Exception)
{
dt = null;
throw;
}
finally
{
if (conn != null)
{
conn.Close();
}
}
return dt;
}
}
```