我创建了一个简单的应用程序,除了更新之外,每个东西都工作正常 部分插入工作正常,具有相同的表数据
我的代码是
private void button2_Click(object sender, EventArgs e)
{
string cmd = ("UPDATE submissionFee SET [stdName]='" + textBox2.Text + "', [fatherName]='" + textBox3.Text + "', [program]='" + textBox4.Text + "', [adress]='" + textBox5.Text + "',[email]='" + textBox6.Text + "', [cellNum]='" + textBox7.Text + "', [isPaid] = '" + textBox8.Text + "', [SubmissionDate] = '" + dateTimePicker1.Value.ToString("MM/dd/yyyy") + "'Where [ID]='" + textBox1.Text + "'");
try
{
connection.Open();
OleDbCommand command = new OleDbCommand();
command.Connection = connection;
command.CommandText = cmd;
command.ExecuteNonQuery();
MessageBox.Show("Account Has Been Updated");
connection.Close();
}
catch (Exception ex)
{
MessageBox.Show("Error " + ex);
MessageBox.Show("Please Enter Valid Data");
}
}
错误截图
答案 0 :(得分:1)
当您尝试打开连接时,可能已经打开了连接。
或者:
1)确保从上次使用时关闭连接。
2)或者,如果它有时应保持打开状态,请检查连接是否已打开,如果已经打开则不要关闭。类似的东西:
bool bWasOpen = (connnection.State == ConnectionState.Open);
if (!bWasOpen)
connection.Open();
...
if (!bWasOpen)
connection.Close();
比崩溃更糟糕:您的代码可以归Sql-injection.
- >使用parameterized sql。
答案 1 :(得分:0)
对话框中此异常的原因是由于连接状态已经打开;因此无法再次打开。您必须在之前的语句中关闭连接。或者,检查连接是否已关闭,然后将其打开。
其他一些提示是
用于将值传递到数据库的用户SQL参数。检查下面的示例陈述
String query = "UPDATE submissionFee SET stdName=@stdName, fatherName=@fatherName where id=@id;";
SqlCommand command = new SqlCommand(query, db.Connection);
command.Parameters.Add("@id",txtID.txt); command.Parameters.Add("@stdName",txtStudent.Text); command.Parameters.Add("@fatherName",txtFatherName.Text);
command.ExecuteNonQuery();
答案 2 :(得分:0)
查询数据库时请使用using statement。 为什么?很简单......它实现了IDisposable。
P.S。 使用参数化查询来防止SQL注入攻击。
string insertStatement = UPDATE submissionFee SET stdName=@stdName,fatherName=@fatherName,program=@program,adress=@adress,email=@email,cellNum=@cellNum,isPaid=@isPaid,SubmissionDate=@SubmissionDate,ID=@ID
using (OleDbConnection connection = new OleDbConnection(connectionString))
using (OleDbCommand command = new OleDbCommand(insertStatement, connection))
command.Parameters.AddWithValue("@ID",textBox1.Text);
command.Parameters.AddWithValue("@stdname",textbox2.Text);
command.Parameters.AddWithValue("@fathername",textBox3.Text);
command.Parameters.AddWithValue("@program",textBox4.Text);
command.Parameters.AddWithValue("@adress",textBox5.Text);
command.Parameters.AddWithValue("@email",textBox6.Text);
command.Parameters.AddWithValue("cellNum",textBox7.Text);
command.Parameters.AddWithValue("@isPaid",textBox8.Text);
command.Parameters.AddWithValue("@SubmissionDate",dateTimePicker1.Value.ToString("MM/dd/yyyy"));
connection.Open();
var results = command.ExecuteNonReader();
}
}