sql-server - 在数据库中保存阿拉伯字符串列表
问题描述
我有 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();
请问我该如何解决这个问题?
解决方案
很可能,您的问题来自插入字符串(作为 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,否则这将无济于事。
推荐阅读
- python - Series 的真值不明确...从 bioinfokit.analys 运行 tukey_hsd 时出错
- google-sheets - 如何从谷歌表格中检索电子邮件编辑器
- reactjs - 如何修复错误延迟加载 React 组件
- swift - 如何构建从不同来源提取数据的 SwiftUI
- arrays - Google Script - 如何在搜索数组中找到嵌套数组的索引?
- python - python flask如何在没有pytz的情况下将给定的字符串日期或日期时间对象转换为utc时间
- laravel - 此集合实例异常中不存在属性 [id]
- spring-jms - 使用 WebSphereMQ 的集群环境中的消息消费
- javascript - 如何从节点js服务器文件传递变量
- flutter - 为什么该列占其父级(容器)的全宽