再加一个 public static DataSet ExecuteDataset(SqlConnection connection, CommandType commandType, string commandText, params SqlParameter[] commandParameters) { //create a command and prepare it for execution SqlCommand cmd = new SqlCommand(); PrepareCommand(cmd, connection, (SqlTransaction)null, commandType, commandText, commandParameters); //create the DataAdapter & DataSet SqlDataAdapter da = new SqlDataAdapter(cmd); DataSet ds = new DataSet(); //fill the DataSet using default values for DataTable names, etc. da.Fill(ds); // detach the SqlParameters from the command object, so they can be used again. cmd.Parameters.Clear(); //return the dataset return ds; }
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Configuration;
using System.Data.SqlClient;
using System.Data;
namespace Login
{
class SqlHelper
{
private static string connStr = ConfigurationManager.ConnectionStrings["connStr"].ConnectionString;
public static object ExecuteScalar(string Sql, params SqlParameter[] parameters)
{
using (SqlConnection conn = new SqlConnection(connStr))
{
conn.Open();
using (SqlCommand cmd = conn.CreateCommand())
{ cmd.CommandText = Sql;
cmd.Parameters.AddRange(parameters);
return cmd.ExecuteScalar();
} }
}
public static DataTable ExecuteDataTable(string Sql, params SqlParameter[] parameters)
{ using (SqlConnection conn = new SqlConnection(connStr))
{
conn.Open();
using (SqlCommand cmd = conn.CreateCommand())
{
cmd.CommandText = Sql;
cmd.Parameters.AddRange(parameters);
DataSet dataset = new DataSet();
SqlDataAdapter adapter = new SqlDataAdapter(cmd);
adapter.Fill(dataset);
return dataset.Tables[0];
}
}
}
public static int ExecuteNonQuery(string Sql, params SqlParameter[] parameters)
{
using (SqlConnection conn = new SqlConnection(connStr))
{
conn.Open();
using (SqlCommand cmd = conn.CreateCommand())
{
cmd.CommandText = Sql;
cmd.Parameters.AddRange(parameters);
return cmd.ExecuteNonQuery(); }
}
}
}
}
你拿了人家的代码吧
这是参数数组
在里面保存sql语句中药使用到的参数,sql语句用@XX代替
相当于定义一个变量,在执行sql语句时把值给语句即可。
params 加上之后就可以在不需要这个参数的时候直接不写。不加的话要写null
public static DataSet ExecuteDataset(SqlConnection connection, CommandType commandType, string commandText, params SqlParameter[] commandParameters)
{
//create a command and prepare it for execution
SqlCommand cmd = new SqlCommand();
PrepareCommand(cmd, connection, (SqlTransaction)null, commandType, commandText, commandParameters); //create the DataAdapter & DataSet
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet(); //fill the DataSet using default values for DataTable names, etc.
da.Fill(ds); // detach the SqlParameters from the command object, so they can be used again.
cmd.Parameters.Clear(); //return the dataset
return ds;
}