首页 > 解决方案 > 在数据库中保存阿拉伯字符串列表

问题描述

我有 ac# 程序。我有字符串列表。该列表的元素是阿拉伯语。当我尝试将列表的元素保存在数据库中时,我看到符号“??????” 这是我的代码

 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();

请问我该如何解决这个问题?

标签: sql-serverlistc#-2.0

解决方案


很可能,您的问题来自插入字符串(作为 varchar)而不是 NVarchar。

如果您在运行循环之前定义参数化查询和参数,您的代码将更可靠、更安全、更快地运行:

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();

最后一点:除非您的数据库将Name列定义为 NVarChar,否则这将无济于事。


推荐阅读