1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
|
/**
* 类说明:对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
这样用上面的操作类来插入中文就不会出现乱码了。