class DBHelper
{
//设置链接数据库为只读
private static readonly string conString = @"server=.\SQL2012;database=Hotel;Integrated Security=sspi";
#region 生成链接对象 SqlConnection CreateConnection()
/// <summary>
/// 生成链接对象
/// </summary>
/// <returns>链接对象</returns>
public static SqlConnection CreateConnection()
{
SqlConnection conn = new SqlConnection(conString);
return conn;
}
#endregion
#region 生成SqlCommand对象SqlCommand CreateCommand(SqlConnection conn, string cmdText, bool isProcedure, params SqlParameter[] parameters)
/// <summary>
/// 生成SqlCommand对象
/// </summary>
/// <param name="conn">SqlCommection对象</param>
/// <param name="cmdText">需要执行的T-SQL语句或存储过程名</param>
/// <param name="isProcedure">标识是否是存储过程,true表示存储过程,false表示T-SQL语句</param>
/// <param name="parameters">命令对象的参数集合</param>
/// <returns>命令对象</returns>
public static SqlCommand CreateCommand(SqlConnection conn, string cmdText, bool isProcedure, params SqlParameter[] parameters)
{
SqlCommand cmd = conn.CreateCommand();
= cmdText;
if (isProcedure)
= CommandType.StoredProcedure;
if (parameters != null)
cmd.Parameters.AddRange(parameters);
return cmd;
}
#endregion
#region
生成DataTable对象DataTable CreateDataTable(SqlCommand cmd)
/// <summary>
/// 生成DataTable对象
/// </summary>
/// <param name="cmd">命令对象</param>
/// <returns>数据表对象</returns>
public static DataTable CreateDataTable(SqlCommand cmd)
{
DataTable dt = new DataTable();
SqlDataAdapter dataAdapter = new SqlDataAdapter(cmd);
dataAdapter.Fill(dt);
return dt;
}
#endregion
#region 加载信息到DataGridView列表 LoadAllInfo(string cmdstr, DataGridView dgv)
/// <summary>
/// 加载信息
/// </summary>
/// <param name="cmdstr">查询字符串</param>
/// <param name="dgv">加载的窗口</param>
public static void LoadAllInfo(string cmdstr, DataGridView dgv)
{
using (SqlConnection conn = new SqlConnection(DBHelper.conString))
{
string sqlselectCmdText = cmdstr;
SqlDataAdapter sqlAdapter = new SqlDataAdapter(sqlselectCmdText, conn);
DataTable dt = new DataTable();
sqlAdapter.Fill(dt);
dgv.DataSource = dt;
}
}
#endregion
}