条件表达式中的数据类型不匹配

时间:2011-03-22 16:56:29

标签: c# visual-studio-2010 ms-access windows-services

我有一个Windows服务,可以将数据插入到某些表中。在调试模式下它确实很好,但是当我安装时它说“标准表达式中的数据类型不匹配”。每个插页。

                        query = "INSERT INTO printers (" +
                            "hostname," +
                            "ip_address," +
                            "model," +
                            "picture_id," +
                            "connect_type," +
                            "status," +
                            "product_number," +
                            "Floor_ID," +
                            "print_corner," +
                            "serial_number," +
                            "printer_features" +
                            ") VALUES ('" +
                            exp.Devices[i].HostName.ToString() + "', '" +
                            exp.Devices[i].IpAddress.ToString() + "', '" +
                            exp.Devices[i].Model.ToString() + "', '" +
                            exp.Devices[i].PictureId.ToString() + "', '" +
                            exp.Devices[i].ConnectType.ToString() + "', '" +
                            exp.Devices[i].Status.ToString() + "', '" +
                            exp.Devices[i].ProductNumber.ToString() + "', '" +
                            exp.Devices[i].Floor.ToString() + "', '" +
                            exp.Devices[i].PrintCorner.ToString() + "', '" +
                            exp.Devices[i].SerialNumber.ToString() + "', '" +
                            exp.Devices[i].PrinterFeatures.ToString() +
                            "')";


        connectionString = "Provider=Microsoft.Jet.OLEDB.4.0; Data Source=" + confParams.MpaSearchDatabase;

        OleDbConnection conn = new OleDbConnection(connectionString);
                        OleDbCommand myCommand = new OleDbCommand(query);
                        myCommand.Connection = conn;
                        conn.Open();
                        myCommand.ExecuteNonQuery();
                        conn.Close();
                        insertedPrintersCount = insertedPrintersCount + 1;

                        Utils.Logger.Info("Device inserted: " + exp.Devices[i].HostName);

帮助!

1 个答案:

答案 0 :(得分:2)

数据类型不匹配错误表示查询期望一种类型的数据,但您提供另一种类型的数据。此查询表达式将每个值作为string字面值传递,但有几列表明它们可能是数值。例如ProductNumberSerialNumber

为了正确传递值(并防止轻松注入攻击),您需要使用OleDbCommand类来构建具有正确类型值的调用。然后让底层基础架构将其转换为适当的值。