使用C#连接MySQL做B/S结构的系统程序出现乱码问题。
解决方法如下:
视图:charset=gbk
控制器:正常...
操作数据库:
StringBuilder strSql = new StringBuilder();
strSql.Append("UPDATE users SET ");
strSql.Append(model.fieldName);
strSql.Append("='");
strSql.Append(model.fieldValue);
strSql.Append("' WHERE userNo='");
strSql.Append(model.userNo);
strSql.Append("'");
return (DbHelperMySQL.ExecuteSql(strSql.ToString()) > 0);
DbHelperMySQL.ExecuteSql源码
public static int ExecuteSql(string SQLString, int Times, params MySqlParameter[] sqlparams)
{
MySqlConnection conn = new MySqlConnection(_connectionString);
MySqlCommand cmd = new MySqlCommand("set names gbk"); //修改了此处。原先MySqlCommand cmd = new MySqlCommand();
try
{
PrepareCommand(cmd, conn, null, CommandType.Text, SQLString, Times, sqlparams);
int rows = cmd.ExecuteNonQuery();
cmd.Parameters.Clear();
return rows;
}
catch
{
throw;
}
finally
{
cmd.Dispose();
if(conn.State == ConnectionState.Open) conn.Close();
conn.Dispose();
cmd = null;
conn = null;
}
}
//经过以上修改后ok!