万能的SQLHelper帮助类
时间:2021-07-01 10:21:17
帮助过:2人阅读
<summary>
/// 数据库帮助类
/// </summary>
public class SQLHelper
{
private static string connStr =
"server=.;database=***;uid=**;pwd=***";
//定义对象
private static SqlConnection conn =
null;
private static SqlCommand cmd =
null;
private static SqlDataAdapter sda =
null;
private static DataSet ds =
null;
/// <summary>
/// 查询多行多列
/// </summary>
public static DataSet Search(
string sql,
params SqlParameter[] parameters)
{
try
{
using (conn =
new SqlConnection(connStr))
{
conn.Open();
cmd =
new SqlCommand(sql, conn);
foreach (SqlParameter p
in parameters)
{
cmd.Parameters.Add(p);
}
sda =
new SqlDataAdapter(cmd);
ds =
new DataSet();
sda.Fill(ds);
return ds;
}
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
finally
{
conn.Close();
}
}
/// <summary>
/// 查询单行单列
/// </summary>
public static object ExecuteScalar(
string sql,
params SqlParameter[] parameters)
{
try
{
using (conn =
new SqlConnection(connStr))
{
conn.Open();
cmd =
new SqlCommand(sql, conn);
foreach (SqlParameter p
in parameters)
{
cmd.Parameters.Add(p);
}
object obj =
cmd.ExecuteScalar();
return obj;
}
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
finally
{
conn.Close();
}
}
/// <summary>
/// 查询单行单列(增删改查)
/// </summary>
public static int ExecuteNonQuery(
string sql,
params SqlParameter[] parameters)
{
try
{
using (conn =
new SqlConnection(connStr))
{
conn.Open();
cmd =
new SqlCommand(sql, conn);
foreach (SqlParameter p
in parameters)
{
cmd.Parameters.Add(p);
}
int row =
cmd.ExecuteNonQuery();
return row;
}
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
finally
{
conn.Close();
}
}
}
万能的SQLHelper帮助类
标签: