在数据库中保存阿拉伯字符串列表

Save list of Arabic strings in database

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

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

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

很可能,您的问题来自插入字符串(作为 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,否则这将无济于事。