最近在做项目,发现在使用Mysql提供给C#操作的类不是和好用,就想办法写了一个操作方便的Mysql数据层类。
比如以前在执 行一个查询
代码
public DataSet Getdataset(long pkid){
string sql="select * from mytable where pkid=@pkid";
MySqlCommand _dbcomm = _dbconn.CreateCommand();
MySqlParameterCollection mysqlparacoll = _dbcomm.Parameters;
mysqlparacoll.Add(new MySqlParameter(n, DbType.Object)
{
Value = 123
});
DbDataAdapter dbad=new MySqlDataAdapter(_dbcomm);
DataSet ds=new DataSet();
dbad.Fill(ds);
return ds;
}
string sql="select * from mytable where pkid=@pkid";
MySqlCommand _dbcomm = _dbconn.CreateCommand();
MySqlParameterCollection mysqlparacoll = _dbcomm.Parameters;
mysqlparacoll.Add(new MySqlParameter(n, DbType.Object)
{
Value = 123
});
DbDataAdapter dbad=new MySqlDataAdapter(_dbcomm);
DataSet ds=new DataSet();
dbad.Fill(ds);
return ds;
}
执行一个简单的带参数的查询语句都要写这么多代码。
下 面展示简单的方法
代码
public DataSet getDataSet(long pkid)
{
string sql="select * from mytable where pkid=@pkid";
using(MyDbHelper db=new MyDbHelper()){
DataSet ds=db.getDataSet(sql,pkid);
return ds;
}
}
//getDataSet Method
/*
public System.Data.DataSet getDataSet(string sql,params object[] paramlist)
{
MySqlCommand dbcomm = CreateDBComm(sql,paramlist);
DbDataAdapter dbad=new MySqlDataAdapter(dbcomm);
DataSet ds=new DataSet();
dbad.Fill(ds);
return ds;
}
*/
{
string sql="select * from mytable where pkid=@pkid";
using(MyDbHelper db=new MyDbHelper()){
DataSet ds=db.getDataSet(sql,pkid);
return ds;
}
}
//getDataSet Method
/*
public System.Data.DataSet getDataSet(string sql,params object[] paramlist)
{
MySqlCommand dbcomm = CreateDBComm(sql,paramlist);
DbDataAdapter dbad=new MySqlDataAdapter(dbcomm);
DataSet ds=new DataSet();
dbad.Fill(ds);
return ds;
}
*/
至 于里面的CreateDBComm(sql,paramlist); 方法我就没有展示了,
这里用到了正则和反射的,自动创建了 MySqlDbType类型的参数。