public class DBHelper
{
//创建数据库连接字符串
public static string constr = "server=.;database=你的数据库名称;Uid=数据库登录用户名;pwd=数据库登录密码";
//数据库连接对象
public static SqlConnection conn = null;
//初始化数据库连接
public static void InitConnection()
{
//如果连接对象不存在,则创建连接
if (conn == null)
{
conn = new SqlConnection(constr);
}
//如果连接对象关闭,则打开连接
if (conn.State == ConnectionState.Closed)
{
conn.Open();
}
//如果连接中断,则重启连接
if (conn.State == ConnectionState.Broken)
{
conn.Close();
conn.Open();
}
}
//获得数据表集
public static DataSet GetDataSet(string strSQL)
{
InitConnection();
//实例化对象
DataSet ds = new DataSet();
SqlDataAdapter dap = new SqlDataAdapter(Sql, Conn);
//填充数据
dap.Fill(ds);
//关闭数据库
Conn.Close();
return ds;
}
//查询,获取DataReader
public static SqlDataReader GetDataReader(string sqlstr)
{
InitConnection();
SqlCommand cmd = new SqlCommand(sqlstr, conn);
return cmd.ExecuteReader(CommandBehavior.CloseConnection);
}
//增删改
public static bool ExecuteNonQuery(string sqlstr)
{
InitConnection();
SqlCommand cmd = new SqlCommand(sqlstr, conn);
int result = cmd.ExecuteNonQuery();
conn.Close();
return result > 0;
}
//执行集合函数
public static object ExecuteScalar(string sqlstr)
{
InitConnection();
SqlCommand cmd = new SqlCommand(sqlstr, conn);
object result = cmd.ExecuteNonQuery();
conn.Close();
return result;
}
}
标签:C#,cmd,DBHelper,static,简单,new,public,conn,sqlstr
From: https://www.cnblogs.com/lucasDC/p/16740487.html