在我开始之前,我会告诉你,在我考虑发布一个问题之前,我已经尝试过在以前的问题和其他网站上已经提出的一切。碰巧,似乎没有任何工作,我只是厌倦了这一点。INSERT INTO命令不起作用
作为一些背景信息,这是为我的计算A2项目,所以我现在有点时间 - 即我不能改变我的代码加载理想。
无论如何,在这个问题上... 我在我的代码中使用SQLCe从各种表读取并写入一个。到目前为止,从表中读取的代码工作正常,所以这是任何连接问题首先。我正在努力的代码如下:
string connectionString = Properties.Settings.Default.BookingSystemDatabaseConnectionString;
using (SqlCeConnection myConnection = new SqlCeConnection(connectionString))
{
myConnection.Open();
try
{
string commandStr = "INSERT INTO bookings(username, room, time) VALUES(@username, @room, @time)";
SqlCeCommand myCommand = new SqlCeCommand(commandStr);
//Passes parameters into SQL command.
myCommand.Parameters.AddWithValue("username", StaticUser.StudentUser.username);
myCommand.Parameters.AddWithValue("room", roomBox.Text);
myCommand.Parameters.AddWithValue("time", timeBox.Text);
//Executes SQL command. Returns the number of affected rows (unecessary for my purposes; a bi-product if you will).
myCommand.ExecuteNonQuery();
}
catch
{
System.Windows.Forms.MessageBox.Show("Could not write new booking to database. This is likely because the database cannot be reached.", "Error");
Program.AccessError = true;
}
myConnection.Close();
}
这只是我试图解决我遇到的问题的很多方法之一。我还探索:
myCommand.Parameters.Add(new SqlCeParameter("username", StaticUser.StudentUser.username));
传递参数,而哪些现在我想不起来了另一种方法(使用“.value的= StaticUser.StudentUser.username”我认为)。此外,我尝试使用命令的'using'语句来保存我自己关闭连接(我可能最终会使用使用'using'的解决方案)。最后(尽管这不是一个年代的回忆),我想:
SqlCeCommand myCommand = new SqlCeCommand("INSERT INTO bookings(username, room, time) VALUES(@username, @room, @time)", myConnection)
再次,当然,也没有用。
为了突出显示我遇到的问题的实际症状:代码似乎运行正常;通过我上面粘贴的完整方法的步骤显示没有错误被捕获(当然,消息框不会出现 - 我后来意识到逐步执行可能是一个不必要的过程),而在其他方法中,我已经谈到了同样的事情发生。那么问题就在于表'预订'实际上并没有被更新。
所以,我的问题,为什么?
我没有做明显的事情,并检查更新的数据库的调试文件夹。
你正在添加'参数的方式很好myCommand.Parameters.AddWithValue',那么你究竟面临迈克尔的问题是什么? – MethodMan 2013-03-25 18:28:27
表'预订'根本没有被写入。没有错误,运行该过程后表格中没有新字段。 – the1mike1man 2013-03-25 18:30:09
您是否检查过以确保您拥有'GRANT权限'来执行更新..?如果MessageBox没有显示它是否碰到你的代码的'catch'部分..? – MethodMan 2013-03-25 18:31:56