使用参数将数据插入access数据库

发布于 2024-11-05 05:01:20 字数 774 浏览 0 评论 0原文

我有以下方法将数据插入到访问数据库中,该方法工作正常,但如果我尝试插入包含我学到的单引号的文本,我确实会遇到问题。

[WebMethod]
public void bookRatedAdd(string title, int rating, string review, string ISBN, string userName)
{
    OleDbConnection conn;
    conn = new OleDbConnection(@"Provider=Microsoft.Jet.OleDb.4.0;
                                               Data Source=" + Server.MapPath("App_Data\\BookRateInitial.mdb"));

    conn.Open();

    OleDbCommand cmd = conn.CreateCommand();

    cmd.CommandText = @"INSERT INTO bookRated([title], [rating],  [review], [frnISBN], [frnUserName])VALUES('" + title + "', '" + rating + "','" + review + "','" + ISBN + "', '" + userName + "')";
    cmd.ExecuteNonQuery();
    conn.Close();
}

据我了解,解决问题的方法之一是使用参数。老实说,我不知道该怎么做。如何更改上述代码以便使用参数插入数据?

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

[WebMethod]
public void bookRatedAdd(string title, int rating, string review, string ISBN, string userName)
{
    OleDbConnection conn;
    conn = new OleDbConnection(@"Provider=Microsoft.Jet.OleDb.4.0;
                                               Data Source=" + Server.MapPath("App_Data\\BookRateInitial.mdb"));

    conn.Open();

    OleDbCommand cmd = conn.CreateCommand();

    cmd.CommandText = @"INSERT INTO bookRated([title], [rating],  [review], [frnISBN], [frnUserName])VALUES('" + title + "', '" + rating + "','" + review + "','" + ISBN + "', '" + userName + "')";
    cmd.ExecuteNonQuery();
    conn.Close();
}

From what I understand one of the ways to solve the problem is by using parameters. I am not sure how to do this to be honest. How could I change the above code so that I insert the data by using parameters instead?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

新雨望断虹 2024-11-12 05:01:20

与任何其他查询相同:

a) 替换 带有占位符的OleDbCommand(以@为前缀),
b) 添加 OleDbParameter 的实例DbCommand.Parameters 属性。参数名称必须与占位符名称匹配。

[WebMethod]
public void bookRatedAdd(string title, int rating, string review, string ISBN, string userName)
{
   using (OleDbConnection conn = new OleDbConnection(
         "Provider=Microsoft.Jet.OleDb.4.0;"+
         "Data Source="+Server.MapPath("App_Data\\BookRateInitial.mdb"));
   {

      conn.Open();

      // DbCommand also implements IDisposable
      using (OleDbCommand cmd = conn.CreateCommand())
      {
           // create command with placeholders
           cmd.CommandText = 
              "INSERT INTO bookRated "+
              "([title], [rating],  [review], [frnISBN], [frnUserName]) "+
              "VALUES(@title, @rating, @review, @isbn, @username)";

           // add named parameters
           cmd.Parameters.AddRange(new OleDbParameter[]
           {
               new OleDbParameter("@title", title),
               new OleDbParameter("@rating", rating),
               ...
           });

           // execute
           cmd.ExecuteNonQuery();
      }
   }
}

Same as for any other query:

a) Replace actual hardcoded parameters in your OleDbCommand with placeholders (prefixed with @),
b) Add instances of OleDbParameter to the DbCommand.Parameters property. Parameter names must match placeholder names.

[WebMethod]
public void bookRatedAdd(string title, int rating, string review, string ISBN, string userName)
{
   using (OleDbConnection conn = new OleDbConnection(
         "Provider=Microsoft.Jet.OleDb.4.0;"+
         "Data Source="+Server.MapPath("App_Data\\BookRateInitial.mdb"));
   {

      conn.Open();

      // DbCommand also implements IDisposable
      using (OleDbCommand cmd = conn.CreateCommand())
      {
           // create command with placeholders
           cmd.CommandText = 
              "INSERT INTO bookRated "+
              "([title], [rating],  [review], [frnISBN], [frnUserName]) "+
              "VALUES(@title, @rating, @review, @isbn, @username)";

           // add named parameters
           cmd.Parameters.AddRange(new OleDbParameter[]
           {
               new OleDbParameter("@title", title),
               new OleDbParameter("@rating", rating),
               ...
           });

           // execute
           cmd.ExecuteNonQuery();
      }
   }
}
甜柠檬 2024-11-12 05:01:20

您必须使用参数来插入值。这也是一个安全问题。
如果你这样做,就可以进行sql注入。

尝试这样:

string ConnString = Utils.GetConnString();
string SqlString = "Insert Into Contacts (FirstName, LastName) Values (?,?)";
using (OleDbConnection conn = new OleDbConnection(ConnString))
{
  using (OleDbCommand cmd = new OleDbCommand(SqlString, conn))
  {
    cmd.CommandType = CommandType.Text;
    cmd.Parameters.AddWithValue("FirstName", txtFirstName.Text);
    cmd.Parameters.AddWithValue("LastName", txtLastName.Text);
    conn.Open();
    cmd.ExecuteNonQuery();
  }
}

You have to use Parameter to insert Values. Its is allso a security Issue.
If you do it like that a sql injection could by made.

Try like this:

string ConnString = Utils.GetConnString();
string SqlString = "Insert Into Contacts (FirstName, LastName) Values (?,?)";
using (OleDbConnection conn = new OleDbConnection(ConnString))
{
  using (OleDbCommand cmd = new OleDbCommand(SqlString, conn))
  {
    cmd.CommandType = CommandType.Text;
    cmd.Parameters.AddWithValue("FirstName", txtFirstName.Text);
    cmd.Parameters.AddWithValue("LastName", txtLastName.Text);
    conn.Open();
    cmd.ExecuteNonQuery();
  }
}
╰沐子 2024-11-12 05:01:20

对于 Microsoft Access,参数是基于位置的且未命名,您应该使用 ? 作为占位符符号,但如果您使用名称参数(只要它们的顺序相同),代码就可以工作。

请参阅 OleDbCommand.Parameters 属性

备注

当 CommandType 设置为 Text 时,OLE DB .NET 提供程序不支持将参数传递给 SQL 语句或 OleDbCommand 调用的存储过程的命名参数。在这种情况下,必须使用问号 (?) 占位符。例如:

从客户中选择 * WHERE CustomerID = ?

因此,将 OleDbParameter 对象添加到 OleDbParameterCollection 的顺序必须直接对应于命令文本中参数的问号占位符的位置。

请务必包含将使用参数的预期架构类型以及架构长度(如果适用)。

我还建议您始终在实例周围使用 using 语句,其中类型像 OleDbConnection 一样实现 IDisposable,以便即使在代码中抛出异常。

更改后的代码:

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

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();
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文