我试过这段代码:
string sql = " DELETE FROM HotelCustomers WHERE [Room Number] =" + textBox1.Text;
OleDbConnection My_Connection = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source= c:\\Users\\Documents\\HotelCustomersOld.mdb");
My_Connection.Open();
OleDbCommand My_Command = new OleDbCommand(sql, My_Connection);
My_Command.ExecuteNonQuery();
错误:条件表达式中的数据类型不匹配: My_Command.ExecuteNonQuery();
答案 0 :(得分:3)
使用参数化查询来避免所有类型的错误
string sql = " DELETE FROM HotelCustomers WHERE [Room Number] =?";
using(OleDbConnection My_Connection = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source= c:\\Users\\Documents\\HotelCustomersOld.mdb"))
{
My_Connection.Open();
OleDbCommand My_Command = new OleDbCommand(sql, My_Connection);
My_Command.Parameters.Add("@p1", textBox1.Text);
My_Command.ExecuteNonQuery();
}
在你的情况下,Room NUmber字段是Text类型,所以你需要将值括在单引号中,但这确实是错误的。您将代码公开给用户在文本框中编写的mathiuos文本。一个非常简单的funny example here
答案 1 :(得分:0)
您的[房间号]列是哪种类型?如果它是一个字符串,那么你必须用反转的逗号或引号来写这个值(我不确定在Access中使用了哪一个)。
string sql = " DELETE FROM HotelCustomers WHERE [Room Number] = '" + textBox1.Text + "'";
为避免SQL损害,您应该使用Parameters而不是字符串操作。
答案 2 :(得分:0)
public static void DeleteLine(string kv)
{
OleDbConnection myConnection = GetConnection();
string myQuery = "DELETE FROM Cloth WHERE [ClothName] = '" + kv + "'";
OleDbCommand myCommand = new OleDbCommand(myQuery, myConnection);
try
{
myConnection.Open();
myCommand.ExecuteNonQuery();
}
catch (Exception ex)
{
Console.WriteLine("Exception in DBHandler", ex);
}
finally
{
myConnection.Close();
}
}
答案 3 :(得分:0)
试
{
OleDbConnection con = new OleDbConnection("provider = microsoft.ace.oledb.12.0;data source = E:\\Sohkidatabase\\Sohki.accdb");
con.Open();
str = "select * from compny_info where id=" + comboBox1.Text.Trim() + "";
com = new OleDbCommand(str, con);
OleDbDataReader reader = com.ExecuteReader();
if (reader.Read())
{
textBox1.Text = reader["regis_no"].ToString();
textBox2.Text = reader["comp_oner"].ToString();
textBox3.Text = reader["comp_name"].ToString();
textBox4.Text = reader["comp_add"].ToString();
textBox5.Text = reader["tin_no"].ToString();
textBox6.Text = reader["email"].ToString();
}
con.Close();
reader.Close();
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
}
答案 4 :(得分:-1)
public static void DeleteLine(string kv) {
OleDbConnection myConnection = GetConnection();
string myQuery = "DELETE FROM Cloth WHERE [ClothName] = '" + kv + "'" ;
}