摘要:大多数据库都支持OleDb,OleDb的参数化查询不支持命名参数,参数用?表示就行,赋值是按顺序赋值的。今天把Sqlserver迁移到Access,顺手写了个简单的OleDbHelper,由于OleDb的通用性,应该也可以访问其它的数据库,而且参数化查询也不怕sql注入,性能应该也会太差。
以下为完整代码,不到50行
1 class OledbHelper
2 {
3 private string _strconn;
4 public OledbHelper(string strconn)
5 {
6 _strconn = strconn;
7 }
8 public T ExecuteScalar<T>(string sql, params object[] args)
9 {
10 using (OleDbConnection conn = new OleDbConnection(_strconn))
11 {
12 return (T)MakeCommand(conn, sql, args).ExecuteScalar();
13 }
14 }
15 public void ExecuteNonQuery(string sql, params object[] args)
16 {
17 using (OleDbConnection conn = new OleDbConnection(_strconn))
18 {
19 MakeCommand(conn, sql, args).ExecuteNonQuery();
20 }
21 }
22 public IDataReader ExecuteReader(string sql, params object[] args)
23 {
24 OleDbConnection conn = new OleDbConnection(_strconn);
25 try
26 {
27 OleDbCommand cmd = MakeCommand(conn, sql, args);
28 return cmd.ExecuteReader(CommandBehavior.CloseConnection);
29 }
30 catch
31 {
32 conn.Close();
33 throw;
34 }
35 }
36 public OleDbCommand MakeCommand(OleDbConnection conn, string sql, params object[] args)
37 {
38 OleDbCommand cmd = new OleDbCommand(sql, conn);
39 if (conn.State != ConnectionState.Open)
40 conn.Open();
41 for (int i = 0; i < args.Length; i++)
42 {
43 cmd.Parameters.AddWithValue(i.ToString(), args[i]);
44 }
45 return cmd;
46 }
47 }
使用示例
//获取单个值
public static string GetTagName(byte tagid)
{
return _db.ExecuteScalar<string>("select TagName from Liwu_Tags where TagId=?", tagid);
}
//普通查询,参数的赋值很自然简单,代码最终也很简短
//需要注意的是access的"日期/时间"列不能用DateTime类型赋值,要ToString一下,如下
public static void AddTags(long itemid, IEnumerable<byte> tagids)
{
foreach (var tagid in tagids)
{
if (!_db.ExecuteReader("select * from Liwu_TagLines where ItemId=? and TagId=?", itemid, tagid).Read())
{
_db.ExecuteNonQuery("insert into Liwu_TagLines values (?,?,?)",
tagid, itemid, DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss"));
}
}
}
//带条件的分页查询,性能还行,查询出来的DataReader可以直接去绑定数据控件去
//分页sql有些长,所以代码有些乱,好在修改的地方不太多
public static IDataReader GetItems(int page = 1, int tagid = -1)
{
const int pagesize = 12;
string sql1 = string.Empty;
if (tagid == -1)
sql1 = string.Format("select top {0} * from Liwu_Items order by CreateTime desc", page * pagesize);
else
sql1 = string.Format("select top {0} item.* from Liwu_Items as item inner join Liwu_TagLines as line"
+ " on line.ItemId = item.ItemId where tagid= ? order by item.CreateTime desc", pagesize * page);
string sql2 = string.Format("select top {0} * from ({1}) order by CreateTime", pagesize, sql1);
string sql = string.Format("select * from ({0}) order by CreateTime desc", sql2);
return tagid == -1 ? _db.ExecuteReader(sql) : _db.ExecuteReader(sql, tagid);
}