![](/img/trans.png)
[英]I am getting Datatype mismatch error due to blank cells in DataGridView
[英]Why am I getting a Datatype Mismatch error in C# Windows Forms Application
我創建了一個簡單的應用程序,除了更新部分插入使用相同的表數據工作正常外,一切正常
我的代碼是
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");
}
}
錯誤截圖
對話框出現這個異常的原因是因為連接狀態已經打開; 因此它無法再次打開。 您必須在之前的語句中關閉連接。 或者,檢查連接是否關閉,然后打開它。
給你的其他一些提示是
使用 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();
查詢數據庫時請使用using 語句。 為什么? 很簡單……它已經實現了IDisposable 。
PS 使用參數化查詢來防止 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();
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.