C#-非拉丁字符在数据库Visual Studio中未正确显示
本文关键字:Studio Visual 显示 数据库 丁字符 字符 C#- | 更新日期: 2023-09-27 18:27:59
这是我的代码,它将动态网格视图的文本框中的元素插入到数据库中。代码运行得很好,但我的问题是,用非拉丁字符(希腊字符)键入的插入元素在数据库中没有正确显示,而是这样显示:
https://i.stack.imgur.com/pwVTf.jpg
你能告诉我怎样才能正确地插入希腊字符吗?这是代码:
private void InsertRecords(StringCollection sc)
{
StringBuilder sb = new StringBuilder(string.Empty);
string[] splitItems = null;
const string sqlStatement = "INSERT INTO P_interventions (Date,P_Id,Simeio,Aitio,Etos,Therap) VALUES";
int id = Convert.ToInt32(Session["pa_id"]);
foreach (string item in sc)
{
if (item.Contains(","))
{
splitItems = item.Split(",".ToCharArray());
sb.AppendFormat("{0}(@Date, @p_id ,'{1}','{2}','{3}','{4}'); ", sqlStatement, splitItems[0], splitItems[1], splitItems[2], splitItems[3]);
}
}
using (SqlConnection connection = new SqlConnection(GetConnectionString()))
{
connection.Open();
using (SqlCommand cmd = new SqlCommand(sb.ToString(), connection))
{
cmd.Parameters.AddWithValue("@p_id", id);
cmd.Parameters.AddWithValue("@Date", DateTime.Now.ToShortDateString());
cmd.CommandType = CommandType.Text;
cmd.ExecuteNonQuery();
}
}
lblMessage.ForeColor = System.Drawing.Color.Green;
lblMessage.Text = "The records have benn inserted successfuly!";
}
protected void BtnSave_Click(object sender, EventArgs e)
{
//εγχειρήσεις
int rowIndex = 0;
StringCollection sc = new StringCollection();
if (ViewState["CurrentTable"] != null)
{
DataTable dtCurrentTable = (DataTable)ViewState["CurrentTable"];
if (dtCurrentTable.Rows.Count > 0)
{
for (int i = 1; i <= dtCurrentTable.Rows.Count; i++)
{
//extract the TextBox values
TextBox box1 = (TextBox)Gridview1.Rows[rowIndex].Cells[1].FindControl("TextBox1");
TextBox box2 = (TextBox)Gridview1.Rows[rowIndex].Cells[2].FindControl("TextBox2");
TextBox box3 = (TextBox)Gridview1.Rows[rowIndex].Cells[3].FindControl("TextBox3");
DropDownList ddl2 = (DropDownList)Gridview1.Rows[rowIndex].Cells[4].FindControl("DropDownList2");
//get the values from TextBox and DropDownList
//then add it to the collections with a comma "," as the delimited values
sc.Add(string.Format("{0},{1},{2},{3}", box1.Text, box2.Text, box3.Text, ddl2.SelectedItem.Text));
rowIndex++;
}
//Call the method for executing inserts
InsertRecords(sc);
}
}
由于您在数据库中使用了nchar字段(如注释中所述),因此您的数据库已经支持Unicode字符串。但是,您正在传递要作为非Unicode字符串文本插入SQL:中的值
'...'
您需要将它们作为Unicode字符串传递:
N'...'
现在不要只在字符串文字前面放一个N
:还有其他错误:通过字符串串联传递用户提供的值,这是一个严重的安全性和稳定性问题。改为使用参数-您已经知道如何使用参数,因为您对@p_id
和@Date
都这样做了。对字符串值执行同样的操作。这也将修复Unicode问题,因为AddWithValue默认为字符串的Unicode参数类型。
我认为您必须在数据库中使用Unicode数据类型,而不是常规数据类型(例如:使用NVarchar而不是Varchar)。
此外,在您的代码中,在字符串字段之前使用N,如
sb.AppendFormat("{0}(@Date, @p_id ,N'{1}',N'{2}',N'{3}',N'{4}'); ", sqlStatement, splitItems[0], splitItems[1], splitItems[2], splitItems[3]);