Save list of Arabic strings in database

我怕爱的太早我们不能终老 提交于 2019-12-13 03:19:21

问题


I have a c# program. I have list of string. The elements of that list in Arabic. When I try to save the elements of list in database I see symbols "??????" Here my code

 List<string> _names = new List<string>()
        {
            "ذهب",
            "قال",
            "تعال",
            "متى",
            "البرمجة",
            "احمد"
        };
       SqlConnection connection = new SqlConnection("Server=DESKTOP-JRS3DQ4; DataBase=Library_DB; Integrated Security=true");
        connection.Open();
        for (int index = 0; index < _names.Count; index++)
        {
            SqlCommand command = new SqlCommand("INSERT INTO tbl_names (id,name) VALUES ('" + index + "', '" + _names[index] + "')", connection);
            command.ExecuteNonQuery();
        }
        connection.Close();

How I can solve this problem please?


回答1:


Most likely, your problem is coming from inserting strings (as varchar) instead of NVarchar.

Your code will work more-reliably, safer & faster if you define a parameterized query and parameters before you run your loop:

List<string> _names = new List<string>()
{
    "ذهب",
    "قال",
    "تعال",
    "متى",
    "البرمجة",
    "احمد"
};
SqlConnection connection = new SqlConnection("Server=DESKTOP-JRS3DQ4; DataBase=Library_DB; Integrated Security=true");
connection.Open();

SqlCommand command = new SqlCommand("INSERT INTO tbl_names (id,name) VALUES (@Id, @Name)", connection);
command.Parameters.Add("@Id", SqlDbType.Int);
command.Parameters.Add("@Name", SqlDbType.NVarChar, 20); //size and type must match your DB

for (int index = 0; index < _names.Count; index++)
{
    command.Parameters["@Id"].Value = index;
    command.Parameters["@Name"].Value = _names[index];
    command.ExecuteNonQuery();
}
connection.Close();

One last note: This will not help unless your DB has the Name column defined as a NVarChar.



来源:https://stackoverflow.com/questions/54791572/save-list-of-arabic-strings-in-database

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