using parameters inserting data into access database

前端 未结 4 1206
无人及你
无人及你 2020-11-22 11:04

I have the following method to inserting data into a an access databasewhich works fine but I do get a problem if I try to insert text that contains single quotes I have lea

4条回答
  •  隐瞒了意图╮
    2020-11-22 11:11

    For Microsoft Access the parameters are positional based and not named, you should use ? as the placeholder symbol although the code would work if you used name parameters provided they are in the same order.

    See the documentation for OleDbCommand.Parameters Property

    Remarks

    The OLE DB .NET Provider does not support named parameters for passing parameters to an SQL statement or a stored procedure called by an OleDbCommand when CommandType is set to Text. In this case, the question mark (?) placeholder must be used. For example:

    SELECT * FROM Customers WHERE CustomerID = ?
    

    Therefore, the order in which OleDbParameter objects are added to the OleDbParameterCollection must directly correspond to the position of the question mark placeholder for the parameter in the command text.

    Be sure to include the expected schema type where the parameter will be used AND the schema length if applicable.

    I also recommend you always use using statements around your instances where the type implements IDisposable like the OleDbConnection so that the connection is always closed even if an exception is thrown in the code.

    Changed Code:

    var connectionStringHere = @"Provider=Microsoft.Jet.OleDb.4.0;Data Source=" + Server.MapPath("App_Data\\BookRateInitial.mdb";
    using (var conn = new OleDbConnection(connectionStringHere))
    using (var cmd = conn.CreateCommand())
    {
        cmd.CommandText = "INSERT INTO bookRated ([title], [rating],  [review], [frnISBN], [frnUserName]) VALUES(?, ?, ?, ?, ?)";
        cmd.Parameters.Add(new OleDbParameter("?", OleDbType.VarChar, 100) { Value = title});
        cmd.Parameters.Add(new OleDbParameter("?", OleDbType.Integer) { Value = rating });
        cmd.Parameters.Add(new OleDbParameter("?", OleDbType.VarChar, 2000) { Value = review });
        cmd.Parameters.Add(new OleDbParameter("?", OleDbType.VarChar, 60) { Value = ISBN });
        cmd.Parameters.Add(new OleDbParameter("?", OleDbType.VarChar, 256) { Value = userName });
    
        conn.Open();
        var numberOfRowsInserted = cmd.ExecuteNonQuery();
    }
    

提交回复
热议问题