数据库操作通用类
优点:达到了sql防注入,并且,将对数据库的操作独立开来,可以提高内聚,降低耦合。达到了哪里使用,哪里关闭的效果,避免隐患。
public class SqlHelper
{
SqlConnection conn = null;
SqlCommand com = null;
SqlDataReader rd = null;
string constr = System.Configuration.ConfigurationManager.ConnectionStrings["my_connect"].ToString();
public bool ConnectSql()
{ // 连接数据库
try
{
conn = new SqlConnection(constr);
conn.Open();
return true;
}
catch
{
return false;
}
}
public bool SqlPour(string sql, Dictionary<string, string> dic)
{ //可完成增删改
try
{
ConnectSql(); //打开连接
com = new SqlCommand(sql, conn);
if(dic != null)
{
foreach(var item in dic)
{
com.Parameters.AddWithValue(item.Key, item.Value);
}
}
com.ExecuteNonQuery();
return true;
}
catch(Exception e)
{
Console.WriteLine(e.Message);
return false;
}
finally //关闭连接
{
closeConn();
}
}
public ArrayList SelectInfo(string sql, Dictionary<string, string> dic)
{ //可完成查找操作,以Object存取放入ArrayList返回
try
{
ConnectSql(); //打开连接
com = new SqlCommand(sql, conn);
ArrayList al = new ArrayList();
if(dic != null)
{
foreach (var item in dic)
{ //遍历参数并进行赋值,防止sql注入
com.Parameters.AddWithValue(item.Key, item.Value);
}
}
rd = com.ExecuteReader();
int clumn = 0; //得到数据的列数
if (rd.Read())
{
clumn = rd.FieldCount;
}
else
{
return null;
}
do
{ //读取每行每列的数据并放入Object数组中
Object[] obj = new object[clumn];
for(int i = 0; i < clumn; i++)
{
obj[i] = rd[i];
}
al.Add(obj); //将一行数据放入数组中
} while (rd.Read());
return al;
}
catch
{
return null;
}
finally
{
closeConn();
}
}
public void closeConn()
{ //关闭数据库连接
try
{
if (conn != null) { conn.Close(); }
if (rd != null) { rd.Close(); }
}
catch
{
return;
}
}
}
使用例子
插入操作
Dictionary<string, string> dic = new Dictionary<string, string>();
insert_sql = "insert into Vote values(@vusername, @vname, @vtime)"; //放置占位符
dic.Add("@vusername", username); //将其放入字典(类似JSON,采用键值对的方式传递)
dic.Add("@vname", vname);
dic.Add("@vtime", DateTime.Now.ToString());
if(!sqlHelper.SqlPour(insert_sql, dic)) { return false; }
更新
Dictionary<string, string> dic = new Dictionary<string, string>();
update_sql = "update Vote set Vname=@vname, Vtime=@vtime where Vusername=@vusername";
dic.Add("@vname", vname);
dic.Add("@vtime", DateTime.Now.ToString());
dic.Add("@vusername", username);
if (!sqlHelper.SqlPour(update_sql, dic)) { return false; }
如果你的sql语句不需要占位符,那就不需要占位符
string sql = "DELETE FROM Person";
if (!sqlHelper.SqlPour(update_sql, null)) { return false; }
切记不可这样使用
string sql = "DELETE FROM @Person";
Dictionary<string, string> dic = new Dictionary<string, string>();
dic.Add("@Person", table_name);
if (!sqlHelper.SqlPour(update_sql, dic)) { return false; }
报错原因:可以看SqlHelper中Parameters.AddWithValue(key, value),它会在sql语句中自动加上’’,也就是说这句话最后会变成DELETE FROM 'Person'
,自然报错。
查找
string sql = "select * from Student where id=@id";
Dictionary<string, string> dic = new Dictionary<string, string>();
dic.Add("@id", id);
ArrayList al = sqlHelper.SelectInfo(sql, dic);
///...判断是否为空跳过,请自行检查,如果报错异常、得到数据为空,则返回null
foreach(Object[] obj in al){ //得到几行数据就能产生多少个对象
Student stu = new Student();
stu.id = (int)obj[0];
//强转成你需要的数据,强转很容易发生异常,所以数据库的约束性要强,对象类时要认真检查数据类型,多用try...catch
stu.name = (string)obj[1];
...
}
总结:可以看出,增删改的操作时大同小异的,可以总结使用方法,用在各个地方进行通用,不用多次编写重复代码。
如果有错误,还请大家指教,有错轻喷,谢谢大家