c#数据库操作类
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Configuration;
using MySql.Data.MySqlClient;
using System.Data;
namespace WindowsFormsApp1
{
public class DBHelper
{
private static readonly String s = ConfigurationManager.ConnectionStrings["connstr"].ConnectionString;
public static int ExecuteNonQuery(string sql,int cmdType,params MySqlParameter[]paras )
{
int count = 0;
using (MySqlConnection conn = new MySqlConnection(s))
{
MySqlCommand cmd = new MySqlCommand(sql, conn);
if (cmdType == 2)
cmd.CommandType = CommandType.StoredProcedure;
if (paras != null && paras.Length > 0)
{
cmd.Parameters.AddRange(paras);
}
conn.Open();
count = cmd.ExecuteNonQuery();
}
return count;
}
public static object ExecuteScalar(string sql, int cmdType, params MySqlParameter[] paras)
{
object o=null;
using (MySqlConnection conn = new MySqlConnection(s))
{
MySqlCommand cmd = new MySqlCommand(sql, conn);
if (cmdType == 2)
cmd.CommandType = CommandType.StoredProcedure;
if (paras != null && paras.Length > 0)
{
cmd.Parameters.AddRange(paras);
}
conn.Open();
o = cmd.ExecuteScalar();
}
return o;
}
public static MySqlDataReader ExecuteReader(string sql, int cmdType, params MySqlParameter[] paras)
{
MySqlDataReader o = null;
MySqlConnection conn = new MySqlConnection(s);
MySqlCommand cmd = new MySqlCommand(sql, conn);
if (cmdType == 2)
cmd.CommandType = CommandType.StoredProcedure;
if (paras != null && paras.Length > 0)
{
cmd.Parameters.AddRange(paras);
}
try
{
conn.Open();
o = cmd.ExecuteReader(CommandBehavior.CloseConnection);
}
catch(MySqlException ex)
{
conn.Close();
throw new Exception("执行查询异常", ex);
}
return o;
}
public static DataTable GetDataTable(String sql, params MySqlParameter[] paras)
{
DataTable o = new DataTable();
using (MySqlConnection conn = new MySqlConnection(s))
{
MySqlCommand cmd = new MySqlCommand(sql, conn);
if (paras != null && paras.Length > 0)
{
cmd.Parameters.AddRange(paras);
}
//conn.Open();
MySqlDataAdapter da = new MySqlDataAdapter();
da.SelectCommand = cmd;
da.Fill(o);
}
return o;
}
}
}