创建一个ProcDBHelper类
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data.SqlClient;
namespace DAL
{
public class DBHelper
{
private readonly static string connection = "Data Source=.;Initial Catalog=Test;User ID=sa;pwd=123321";
/// <summary>
/// 存储过程增删改
/// </summary>
/// <param name="type">表示执行时的类别</param>
/// <param name="procSql">存储过程名称、sql语句、表名</param>
/// <param name="par">参数</param>
/// <returns></returns>
public int SqlExec(CommandType type, string procSql,SqlParameter[] par)
{
try
{
using (SqlConnection conn = new SqlConnection(connection))
{
conn.Open();
SqlCommand command = new SqlCommand(procSql, conn);
command.CommandType = type;
if(par!=null)
{
command.Parameters.AddRange(par);
}
return command.ExecuteNonQuery();
}
}
catch
{
return -1;
}
}
/// <summary>
/// 存储过程调用
/// </summary>
/// <param name="type">表示执行时的类别</param>
/// <param name="procName"></param>
/// <param name="par"></param>
/// <returns></returns>
public DataTable GetProcDataTable(CommandType type, string procName, SqlParameter[] par)
{
try
{
using (SqlConnection conn = new SqlConnection(connection)) //连接数据库
{
SqlCommand command = new SqlCommand(procName, conn); //执行SQL语句
command.CommandType = type;
if (par != null)
{
command.Parameters.AddRange(par);
}
SqlDataAdapter sda = new SqlDataAdapter(command); //适配器
DataTable dt = new DataTable(); //NEW DataTable
dt.TableName = "dt";
sda.Fill(dt); //填充数据
return dt;
}
}
catch (Exception)
{
return null;
}
}
}
}