ADO.NET 总结(2)
来源:未知 责任编辑:责任编辑 发表时间:2014-01-06 18:19 点击:次
开始 –> 所有程序 –> Microsoft SQL Server 2005 –> Configuration Tools –> SQL Server configuration Manager –> 重启数据库服务.
四、使用MySql中文乱码问题
1、修改my.ini
[mysqld] default-character-set=utf8
2、没有权限修改my.ini
假设数据库采用了默认编码latin1,经研究发现:
1. Select出的数据需要将其从拉丁文转化为GBK
2. 传入的SQL语句需要将其从GBK转化为拉丁文
public static class DBHelper { public static T Get<T>(DbDataRecord record,string field) { int num = record.GetOrdinal(field); if(record.IsDBNull(num)) return default(T); return (T)record[num]; } publicstatic int? ToInt32(object value) { if (value == null) return null; return((IConvertible)value).ToInt32(null); } public static voidAddParameter(string name, object value, DbCommand cmd) { DbParameter para =cmd.CreateParameter(); para.ParameterName =string.Format(ParameterMarkerFormat, name); if (value == null) para.Value =DBNull.Value; else para.Value = value; cmd.Parameters.Add(para); } publicstatic String LatinToGBK(String str) { try { byte[] bytesStr =Encoding.GetEncoding("latin1").GetBytes(str); returnEncoding.GetEncoding("GB2312").GetString(bytesStr); } catch { return str; }} public static String GBKToLatin(String str) { try { byte[] bytesStr =Encoding.GetEncoding("GB2312").GetBytes(str); returnEncoding.GetEncoding("latin1").GetString(bytesStr); } catch { return str; }} public static string ParameterMarkerFormat =DbProviderFactoryEx.SqlServerParameterMarkerFormat; }
应用
// 处理DbDataReader using (DbDataReader reader = cmd.ExecuteReader()) {foreach (DbDataRecord record in reader) { role.ID = DBHelper.Get<uint>(record, "ID"); role.Name = DBHelper.LatinToGBK(DBHelper.Get<string>(record, "RoleName")); role.Account =DBHelper.LatinToGBK(DBHelper.Get<string>(record, "Account")); return true;} } // 处理DataTable foreach (DataRow row in table.Rows) {row["OperationType"] =DBHelper.LatinToGBK(row["OperationType"].ToString());row["OperationReason"] =DBHelper.LatinToGBK(row["OperationReason"].ToString()); } // 传入的SQL语句DbCommand cmd = conn.CreateCommand(); cmd.CommandText = "select * from role where rolename=?rolename"; DBHelper.AddParameter("rolename",DBHelper.GBK2Latin(name), cmd);
作者 CppExample.com
相关新闻>>
最新推荐更多>>>
- 发表评论
-
- 最新评论 更多>>