我通过WCF服务连接到一个紧凑的SQL数据库服务器,并在Command.ExecuteNonQuery()
上继续获得以下内容。我试过解决这个问题但只是不知道出了什么问题。
例外:
发生了'System.Data.SqlServerCe.SqlCeException'类型的异常 在System.Data.SqlServerCe.dll中但未在用户代码中处理
代码:
//The connectionString can be found in the properties table of the database
string connString = "Data Source=C:\\Users\\User\\documents\\visual studio 2012\\Projects\\ADO_LINQ\\ADO_LINQ\\App_Data\\MyDatabase.sdf;Persist Security Info = False";
SqlCeConnection myConnection = new SqlCeConnection(connString);
myConnection.Open();
// Create the query
string myQuery = "INSERT INTO Player " +
" VALUES (" + registrationID + "," +
firstName + ", " +
lastName + ", " +
phoneNumber + ", " +
address + ", " +
dateOfBirth + ");";
//Initialuze the command
SqlCeCommand myCommand = new SqlCeCommand(myQuery, myConnection);
//Run the command
myCommand.ExecuteNonQuery();
//Close the connection
myConnection.Close();
答案 0 :(得分:3)
您缺少字符串数据类型的单引号,假设只有registrationID是Integer数据类型而所有其他列都是String数据类型,您的查询应该看起来像......
// Create the query
String myQuery = "INSERT INTO Player " +
" VALUES (" + registrationID + ", '"+ firstName +"' , '"+lastName+"' , '"+phoneNumber+ "', '"+ address +"', '"+dateOfBirth+"' );";
更好更安全的选择是使用参数化查询。这样的东西......
String connString = @"Data Source=C:\Users\User\documents\visual studio 2012\Projects\ADO_LINQ\ADO_LINQ\App_Data\MyDatabase.sdf;Persist Security Info = False";
using(SqlCeConnection myConnection = new SqlCeConnection(connString))
{
// Create the query
String myQuery = "INSERT INTO Player " +
" VALUES (@registrationID , @firstName , @lastName , @phoneNumber, @address , @dateOfBirth );";
//Initialuze the command
SqlCeCommand myCommand = new SqlCeCommand(myQuery, myConnection);
// Add parameters
myCommand.Parameters.AddWithValue("@registrationID" ,registrationID);
myCommand.Parameters.AddWithValue("@firstName" , firstName);
myCommand.Parameters.AddWithValue("@lastName" , lastName);
myCommand.Parameters.AddWithValue("@phoneNumber" , phoneNumber);
myCommand.Parameters.AddWithValue("@address" , address);
myCommand.Parameters.AddWithValue("@dateOfBirth" , dateOfBirth);
//Open Connection
myConnection.Open();
//Run the command
myCommand.ExecuteNonQuery();
}