2

我试过这段代码:

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();

4

5 回答 5

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 类型,因此您需要将值括在单引号中,但这确实是错误的。您将代码暴露给用户在文本框中编写的恶意文本。这里有一个非常简单有趣的例子

于 2013-04-19T18:38:38.680 回答
1

您的 [房间号] 列是哪种类型?如果它是一个字符串,那么你必须用引号或引号写入值(我不确定在 Access 中使用了哪一个)。

string sql = " DELETE FROM HotelCustomers WHERE [Room Number] = '" +  textBox1.Text + "'";

为避免 SQL 注入,您应该使用参数而不是字符串操作。

于 2013-04-19T18:40:06.533 回答
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();
    }
}
于 2015-04-07T09:16:42.893 回答
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);
        }
于 2016-07-02T11:35:05.747 回答
-1
 public static void DeleteLine(string kv) {
      OleDbConnection myConnection = GetConnection();
      string myQuery = "DELETE FROM Cloth WHERE [ClothName] = '" + kv + "'" ;
 }
于 2015-04-07T09:20:30.170 回答