问题
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