using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Data.SqlClient;namespace AddressBook
{
class SqlHelper
{
/// <summary>
/// 连接数据库的字符串
/// </summary>
private static string connectionString = System.Configuration.ConfigurationManager.ConnectionStrings["connStr"].ConnectionString;/// <summary>
/// 返回一个DataTable结果集
/// </summary>
/// <param name="sql">sql语句</param>
/// <param name="sqlParameter">sql语句中的参数</param>
/// <returns>DataTable</returns>
public static DataTable ExecuteDataTable(string sql, params SqlParameter[] sqlParameter)
{
DataSet ds = new DataSet(); //创建一个表在内存里
//创建适配器对象
SqlDataAdapter adapter = new SqlDataAdapter(sql, connectionString);
//添加参数到Adapter的selectCommand命令中
adapter.SelectCommand.Parameters.AddRange(sqlParameter);
try
{
adapter.Fill(ds); //填充ds
return ds.Tables[0];//返回ds数据集中第一个表
}
catch
{
return null;
}
finally
{
adapter.Dispose(); //清理资源
}
}/// <summary>
/// 返回增/删/改 受影响的行数
/// </summary>
/// <param name="sql">sql语句</param>
/// <param name="sqlParameter">sql语句中的参数</param>
/// <returns>int</returns>
public static int ExecuteNonQuery(string sql, params SqlParameter[] sqlParameter)
{
using (SqlConnection conn = new SqlConnection(connectionString))
{
using (SqlCommand cmd = new SqlCommand(sql, conn))
{
cmd.Parameters.AddRange(sqlParameter);
conn.Open();
return cmd.ExecuteNonQuery();
}
}
}/// <summary>
/// 返回查询的首行首列
/// </summary>
/// <param name="sql">sql语句</param>
/// <param name="sqlParameter">sql语句中的参数</param>
/// <returns></returns>
public static object ExecuteScalar(string sql, params SqlParameter[] sqlParameter)
{
using (SqlConnection conn = new SqlConnection(connectionString))
{
using (SqlCommand cmd = new SqlCommand(sql, conn))
{
cmd.Parameters.AddRange(sqlParameter);
conn.Open();
return cmd.ExecuteScalar();
}
}
}}
}
SqlHelper 简单版