SqlCeCommand一直给我一个异常
本文关键字:一个 异常 一直 SqlCeCommand | 更新日期: 2023-09-27 18:27:50
我正在通过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();
您的字符串数据类型缺少单引号,假设只有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();
}