c# mysql 中文乱码
时间: 2023-12-14 11:34:29 浏览: 126
在C#程序中操作MySQL数据库时,中文乱码问题可能会出现。解决方法如下:
1.在连接MySQL数据库时,需要设置字符集为utf8,以确保中文数据的正确存储和读取。示例代码如下:
```csharp
string connStr = "server=localhost;user=root;database=test;port=3306;password=123456;charset=utf8";
MySqlConnection conn = new MySqlConnection(connStr);
```
2.在执行SQL语句时,需要将中文字符串转换为utf8编码的字节数组,并使用MySqlParameter对象将其传递给SQL语句。示例代码如下:
```csharp
string name = "张三";
byte[] nameBytes = Encoding.UTF8.GetBytes(name);
MySqlParameter param = new MySqlParameter("@name", MySqlDbType.VarBinary, nameBytes.Length);
param.Value = nameBytes;
string sql = "INSERT INTO user(name) VALUES(@name)";
MySqlCommand cmd = new MySqlCommand(sql, conn);
cmd.Parameters.Add(param);
cmd.ExecuteNonQuery();
```
3.在读取中文数据时,需要将读取到的字节数组转换为中文字符串。示例代码如下:
```csharp
string sql = "SELECT name FROM user WHERE id=1";
MySqlCommand cmd = new MySqlCommand(sql, conn);
MySqlDataReader reader = cmd.ExecuteReader();
if (reader.Read())
{
byte[] nameBytes = (byte[])reader["name"];
string name = Encoding.UTF8.GetString(nameBytes);
Console.WriteLine(name);
}
```
阅读全文