【问题标题】:problems with command.ExecuteNonQuery(); when working with databases Please help, for assignmentcommand.ExecuteNonQuery() 的问题;使用数据库时请帮忙,分配
【发布时间】:2014-09-02 08:15:44
【问题描述】:

这是我的代码

namespace SDD_Single_Project___Michael
{
    public partial class NewUser : Form
    {
        private OleDbConnection connection = new OleDbConnection();

        public NewUser()
        {
            InitializeComponent();
            connection.ConnectionString = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=G:\schoolwork\Year 11\SDD\3 SINGLE TASK\SDD Single Project - Michael \SDD Single Project - Michael \bin\Persondata.accdb;
Persist Security Info=False;";
    }

    private void btnBack_Click(object sender, EventArgs e)
    {
        this.Hide(); //hides this page
        MainScreen frm = new MainScreen(); //finds the next screen (the main game)
        frm.Show(); //shows it
    }

    private void btnSubmit_Click(object sender, EventArgs e)
    {
        try {
               connection.Open(); // opens the connection
               OleDbCommand command = new OleDbCommand();
               command.Connection = connection;
               command.CommandText = "insert into Persondata  where  ( FirstName,LastName,Address,Suburb,Email,Mobile) values ( '" + txtFirst.Text + "' , '" + txtLast.Text + "' , '" + txtAddress.Text + "' , '" + txtSuburb.Text + "' , '" + txtEmail.Text + "' , '" + txtMobile.Text + "' ) ";
               // finds where its going to, finds the columns it is going to fill, finds the text boxes that is going to fill them

               command.ExecuteNonQuery();  // error occurs here!!!
               MessageBox.Show("Data Saved");
               connection.Close(); // closes the connection
           }
           catch (Exception ex)
           { 
               MessageBox.Show("Error   " + ex); 
           } //if there is a error message box will appear informing it 
        }
    }
}

错误发生在command.ExecuteNonQuery();,我无法修复它,一旦我将所有信息填写到文本框中并按下提交按钮,错误就会发生。

错误说这是INSERT INTO语句中的语法错误

System.Data.Ole.DbCommand.ExecuteNonQuery(); 

请帮忙!是为了任务!我一直在努力解决它。感谢所有帮助。

【问题讨论】:

  • 您应该始终使用parameterized queries。这种字符串连接对SQL Injection 攻击开放。
  • 这里出现错误!!!什么错误?发布异常详情。
  • Prewarning about sql injection.. 到目前为止你尝试过什么?您是否确认该表存在?发布完整的错误消息以启动和重现问题所需的最少代码。
  • 如果从插入语句中删除where 关键字会怎样?

标签: c# oledbconnection executenonquery


【解决方案1】:

INSERT syntax 中没有 WHERE 部分。你应该从你的 sql 中删除它。

INSERT 
{
        [ TOP ( expression ) [ PERCENT ] ] 
        [ INTO ] 
        { <object> | rowset_function_limited 
          [ WITH ( <Table_Hint_Limited> [ ...n ] ) ]
        }
    {
        [ ( column_list ) ] 
        [ <OUTPUT Clause> ]
        { VALUES ( { DEFAULT | NULL | expression } [ ,...n ] ) [ ,...n     ] 
        | derived_table 
        | execute_statement
        | <dml_table_source>
        | DEFAULT VALUES 
        }
    }
}

OleDbCommand 不支持命名参数。

来自OleDbCommand.Parameters property

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

SELECT * FROM Customers WHERE CustomerID = ?

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

如果集合中的参数不符合要求 要执行的查询,可能会导致错误。

但更重要的是,您应该始终使用parameterized queries。这种字符串连接对SQL Injection 攻击开放。

command.CommandText = @"insert into Persondata(FirstName,LastName,Address,Suburb,Email,Mobile) 
                       values (?, ?, ?, ?, ?, ?)";

然后用SqlParameterCollection.Add method添加你的参数值

也可以使用using statement 来处理您的数据库连接。

using(OleDbConnection connection = new OleDbConnection(connString))
using(OleDbCommand command = connection.CreateCommand())
{
      command.CommandText = @"insert into Persondata(FirstName,LastName,Address,Suburb,Email,Mobile) 
                              values (?, ?, ?, ?, ?, ?)";
      //Add your parameter values with right order.
      connection.Open();
      command.ExecuteNonQuery();
}

【讨论】:

    【解决方案2】:

    您的应用程序中的 SQL 语句不正确。插入 SQL 子句不允许使用 where。这是MSDN的节选,结构为INSERT INTO子句。

    [ WITH <common_table_expression> [ ,...n ] ] INSERT  {
            [ TOP ( expression ) [ PERCENT ] ] 
            [ INTO ] 
            { <object> | rowset_function_limited 
              [ WITH ( <Table_Hint_Limited> [ ...n ] ) ]
            }
        {
            [ ( column_list ) ] 
            [ <OUTPUT Clause> ]
            { VALUES ( { DEFAULT | NULL | expression } [ ,...n ] ) [ ,...n     ] 
            | derived_table 
            | execute_statement
            | <dml_table_source>
            | DEFAULT VALUES 
            }
        } } [;]
    

    使用 SQL 语句的正确方法是(也取自 MSDN):

    INSERT INTO Production.UnitMeasure
    VALUES (N'FT', N'Feet', '20080414');
    

    如果您使用的是 SELECT INTO 语句,则可以使用 where。

    因此,要解决您的问题,您需要从 SQL 语句中删除 where 子句

    【讨论】:

    • @user1999222 抱歉,您为什么接受这个答案?我认为其他答案的质量更好..
    【解决方案3】:

    你不应该在INSERT 语句中使用WHERE

     command.CommandText = "insert into Persondata  ( FirstName,LastName,Address,Suburb,Email,Mobile) values ( @param1,@param2,@param3,@param4,@param5,@param6) ";
     command.Parameters.AddWithValue("@param1", txtFirst.Text);
     command.Parameters.AddWithValue("@param2",txtLast.Text);
    ....
    ...
    command.Parameters.AddWithValue("@param6",txtMobile.Text);
    

    【讨论】:

    • 错字..意思是不应该
    • 这更有意义! :-)
    • 另外OleDbCommand 不支持命名参数。您需要改用?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-03-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-04-27
    • 1970-01-01
    相关资源
    最近更新 更多