我有一个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();
请问如何解决这个问题?
答案 0 :(得分:1)
很有可能,您的问题出在插入字符串(如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,否则这将无济于事。