【发布时间】:2014-10-22 07:32:26
【问题描述】:
因此,我在 C# 中创建并调用了 WCF 服务,但一直收到错误回复,我不确定为什么会这样。这可能与连接字符串有关,但从当前更改它只会给我错误。
这是我的代码:
//Create the new connection
SqlConnection myConnection = new SqlConnection();
//Create the query
String myQuery = "INSERT INTO Player (registrationID, firstName, lastName, phoneNumber, Address, dateOfBirth) " +
" VALUES ('" + registrationID + "', '" + firstName + "', '" + lastName + "', '" + phoneNumber + "', '" + Address + "', '" + dateOfBirth + "');";
//The connectionString can be found in the properties table of the database
myConnection.ConnectionString = "Data Source=C:/Users/User/Documents/Visual Studio 2012/Projects/ADO_LINQ/ADO_LINQ/App_Data/MyDatabase.sdf";
//Initialuze the command
SqlCommand myCommand = new SqlCommand(myQuery, myConnection);
SqlDataReader myReader;
//Run the command
try
{
myConnection.Open();
myReader = myCommand.ExecuteReader();
//Return true if it was successful
return true;
}
catch (Exception ex)
{
return false;
}
【问题讨论】:
-
您是否尝试过删除
catch块,以便服务崩溃并告诉您出了什么问题? -
有什么错误?您应该始终使用parameterized queries。这种字符串连接对SQL Injection 攻击开放。由于您使用的是
INSERT语句,因此没有必要使用ExecuteReader。因为您的查询不返回任何数据,它只是插入数据。只需改用ExecuteNonQuery。还可以使用using语句来处理您的数据库连接和对象。 -
如果你不对异常做任何事情(例如,记录它或其他什么),那么捕获异常就没有什么意义了。遇到异常时简单地返回 false 意味着您正在吞下该异常,这将使故障排除变得很痛苦。
标签: c# sql database wcf ado.net