Insert unicode text in MySql4 throught ASP.NET

别说谁变了你拦得住时间么 提交于 2021-01-29 16:25:52

问题


I'm writing a new website for an institute which has 4000 users that are stored in MySql4 !

I'm using mysql-connector/net to connect to MySql database throught asp.net,

Everything is OK, EXCEPT updating the info which are in unicode mode !

Unfortunately I don't know lot about unicode !

Connecting and reading data from MySql database is like this :

using MySql.Data.MySqlClient;
...
MySqlConnection con;
MySqlCommand cmd;

string tempstr = "Database=DB-NAME;Data Source=SOURCE;charset=utf8;User Id=USER;Password=PASS";
con = new MySqlConnection(tempstr);
con.Open();
cmd = con.CreateCommand();
cmd.CommandText = "select * from list_membership";
cmd.CommandType = CommandType.Text;
MySqlDataReader reader = cmd.ExecuteReader();
reader.Read();

Now when I read an address for example I get sth like this: زÙجاÙ

Fortunately I've solved it using the function blew:

public string DecodeFromUtf8(string utf8String)
{
   // copy the string as UTF-8 bytes.
   byte[] utf8Bytes = new byte[utf8String.Length];
   for (int i = 0; i < utf8String.Length; ++i)
   {
       //Debug.Assert( 0 <= utf8String[i] && utf8String[i] <= 255, "the char must be in byte's range");
       utf8Bytes[i] = (byte)utf8String[i];
   }
   return Encoding.UTF8.GetString(utf8Bytes, 0, utf8Bytes.Length);
}

Now I send the junky string to the function and I get correct form like this : زنجان (persian language)

The problem is that when I want to update or insert address field for instance, nothing will store in the database except some question marks like this: ???? ?????

Anyone know what should I do ?! Is there any reverse form for DecodeFromUtf8 function ?

Excuse my bad english, Thanks.


回答1:


I don't know if this helps with the problem, but the reverse of DecodeFromUtf8 should look something like this:

public string EncodeToMySQL4(string str)
{
   Encoding latin1 = new Encoding(1252);
   return latin1.GetString(Encoding.UTF8.GetBytes(str));
}


来源:https://stackoverflow.com/questions/18186741/insert-unicode-text-in-mysql4-throught-asp-net

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!