近期学习C#中,希望点滴的记录能促进我的进步
解决乱码之前首先你需要了解,你的Mysql数据库的字符集是否已经设置成统一的(这里以gb2312示例),如果没有先设置
具体设置方法网上相关资料很多,关键字:Mysql字符集设置
其次,在你建立数据库时字符集是否设置成gb2312了,特别是使用UI工具时
如果都设置了,那么请关注你的代码:
MySQLConnection conn = new MySQLConnection(new MySQLConnectionString("localhost", "bms", "root", "root", 3306).AsString);
conn.Open();
MySQLCommand commn = new MySQLCommand("set names gb2312" , conn);
commn.ExecuteNonQuery(); //这里是设置结果集,如果不设置是乱码,经测试
/*获得数据的方法一,个人不太习惯用这方法
string sql = "select * from t_user";
MySQLDataAdapter mda = new MySQLDataAdapter(sql, conn);
DataSet ds = new DataSet();
mda.Fill(ds, "ri");
for (int i = 0; i < ds.Tables[0].Rows.Count;i++ ){
Console.WriteLine(ds.Tables[0].Rows[i][1].ToString());
}*/
/*再创建一次 command 执行SQL语句,我觉得这个方法和Java的类似
MySQLCommand comm = new MySQLCommand("select * from t_user", conn);
MySQLDataReader DBReader = comm.ExecuteReaderEx();
try {
while (DBReader.Read())
{
Console.WriteLine("Host = {0} and User = {1}",
DBReader.GetString(0), DBReader.GetString(1));
}
}
finally
{
DBReader.Close();
}
conn.Close();