把MySqlXXX的类更改为SqlXXX就可以成为sqlHelper.
另外C#也提供了MysqlHelper和sqlHelper,用起来也挺方便的。
public class MySqlHelper
{
private static readonly string connstr = ConfigurationManager.ConnectionStrings["connstr"].ConnectionString;
public MySqlConnection CreateConnection()
{
MySqlConnection conn = new MySqlConnection(connstr);
conn.Open();
return conn;
}
public int ExecuteNonQuery(string sql,params MySqlParameter[]parameters)
{
using (MySqlConnection conn=CreateConnection())
using(MySqlCommand cmd=conn.CreateCommand())
{
cmd.CommandText = sql;
cmd.Parameters.AddRange(parameters);
return cmd.ExecuteNonQuery();
}
}
public object ExecuteScalar(string sql,params MySqlParameter[]parameters)
{
using (MySqlConnection conn=CreateConnection())
using (MySqlCommand cmd=conn.CreateCommand())
{
cmd.CommandText = sql;
cmd.Parameters.AddRange(parameters);
return cmd.ExecuteScalar();
} } public MySqlDataReader ExecuteReader(string sql,params MySqlParameter[]ps)
{
using (MySqlConnection conn=CreateConnection())
using(MySqlCommand cmd=conn.CreateCommand())
{
cmd.CommandText = sql;
if (ps!=null)
{
cmd.Parameters.AddRange(ps);
}
return cmd.ExecuteReader();
}
}
public DataTable ExecuteDataTable(string sql,params MySqlParameter[]ps)
{
DataTable table = new DataTable();
using (MySqlConnection conn=CreateConnection())
using(MySqlCommand cmd=conn.CreateCommand())
{
cmd.CommandText = sql;
if (ps!=null)
{
cmd.Parameters.AddRange(ps);
}
using ( MySqlDataAdapter adapter = new MySqlDataAdapter(cmd))
{
adapter.Fill(table);
}
return table;
}
}
}