欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

一个ASP.NET的MYSQL的数据库操作类自己封装的

程序员文章站 2024-02-24 21:47:10
/** * 类说明:对mysql数据库的操作类 */ using system; using system.data; using mysql....
/** 
* 类说明:对mysql数据库的操作类 
*/ 
using system; 
using system.data; 
using mysql.data.mysqlclient; 


namespace niunan.bylw.utility 
{ 
/// <summary>对mysql数据库的操作类 
/// 
/// </summary> 
public class mysqlhelper 
{ 
private mysqlconnection conn = null; 
private mysqlcommand cmd = null; 
private mysqldatareader sdr = null; 


public mysqlhelper() 
{ 
//string connstr = webconfigurationmanager.connectionstrings["connstr"].tostring(); 
string connstr = "server=localhost;database=test;uid=root;pwd=123456;charset=utf8"; 
conn = new mysqlconnection(connstr); 
} 


/// <summary>创建command对象 
/// 
/// </summary> 
/// <param name="sql">sql语句</param> 
public void createcommand(string sql) 
{ 
conn.open(); 
cmd = new mysqlcommand(sql, conn); 
} 


/// <summary>添加参数 
/// 
/// </summary> 
/// <param name="paramname">参数名称</param> 
/// <param name="value">值</param> 
public void addparameter(string paramname, object value) 
{ 
cmd.parameters.add(new mysqlparameter(paramname, value)); 
} 


/// <summary>执行不带参数的增删改sql语句 
/// 
/// </summary> 
/// <param name="cmdtext">增删改sql语句</param> 
/// <param name="ct">命令类型</param> 
/// <returns></returns> 
public bool executenonquery() 
{ 
int res; 
try 
{ 
res = cmd.executenonquery(); 
if (res > 0) 
{ 
return true; 
} 
} 
catch (exception ex) 
{ 
throw ex; 
} 
finally 
{ 
if (conn.state == connectionstate.open) 
{ 
conn.close(); 
} 
} 
return false; 
} 


/// <summary>执行查询sql语句 
/// 
/// </summary> 
/// <param name="cmdtext">查询sql语句</param> 
/// <returns></returns> 
public datatable executequery() 
{ 
datatable dt = new datatable(); 
using (sdr = cmd.executereader(commandbehavior.closeconnection)) 
{ 
dt.load(sdr); 
} 
return dt; 
} 


/// <summary>返回查询sql语句查询出的结果的第一行第一列的值 
/// 
/// </summary> 
/// <returns></returns> 
public string executescalar() 
{ 
string res = ""; 
try 
{ 
object obj = cmd.executescalar(); 
if (obj != null) 
{ 
res = obj.tostring(); 
} 
} 
catch (exception ex) 
{ 
throw ex; 
} 
finally 
{ 
if (conn.state == connectionstate.open) 
{ 
conn.close(); 
} 
} 
return res; 
} 
} 
} 

都是把那个sqlitehelper的操作类搬过来的,改了mysqlconnection等变量名,对mysql来说经常会出现中文乱码,经实验,解决方法:

① 用phpmyadmin建立mysql数据库的时候记得选择utf-8的编码

② 在上面的数据库操作类中的连接字符串中记得加上charset=utf8

这样用上面的操作类来插入中文就不会出现乱码了。