我正在尝试将单个值插入 SQL 数据库。只要我不插入“\”,它就可以正常工作。如果这样做,那么我会在数据库中丢失一个“\”。
例如,在调试器中我看到以下命令文本:
Insert into tblProjekte (Projektbezeichnung) values ('\\bla\\bla\\bla')
但是在 SQL Server Profiler 中我总是找到这个插入语句:
Insert into tblProjekte (Projektbezeichnung) values ('\bla\bla\bla')
我的源代码:
public void InsertProjekt(string Projektbezeichnung)
{
SqlConnection con = new SqlConnection();
con.ConnectionString = "Server=localhost; Database=myProjekt; UID=user; PWD=pwd";
con.Open();
SqlCommand com = new SqlCommand();
com.Connection = con;
com.CommandText = String.Format("Insert into tblProjekte (Projektbezeichnung) values ('{0}')",@Projektbezeichnung);
int rows = com.ExecuteNonQuery();
}
在我将源代码更改为:
SqlCommand com = new SqlCommand("INSERT INTO tblProjekte (Projektbezeichnung) VALUES (@Projektbezeichnung)");
com.Parameters.AddWithValue("@Projektbezeichnung", Projekt.Projektbezeichnung);
我在调试过程中得到以下信息:
值为“\\Tesafilm” SQLValue 是“\Tesafilm”
最佳答案
使用 parametrized query相反:
public void InsertProjekt(string Projektbezeichnung)
{
SqlConnection con = new SqlConnection();
con.ConnectionString = "Server=localhost; Database=myProjekt; UID=user; PWD=pwd";
con.Open();
SqlCommand com = new SqlCommand();
com.Connection = con;
com.CommandText = "Insert into tblProjekte (Projektbezeichnung) values (@value)"
com.Parameters.AddWithValue("@value", Projektbezeichnung);
int rows = com.ExecuteNonQuery();
}
关于c# - 使用 ExecuteNonQuery 时丢失\,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17969257/