【问题标题】:Syntax error in INSERT INTO statement for MS AccessMS Access 的 INSERT INTO 语句中的语法错误
【发布时间】:2011-09-22 11:34:58
【问题描述】:

我有一个在正常情况下工作的 SQL Insert Into 命令。这意味着如果我填写每个文本框,数据就会发送到数据库(访问数据库)。

但当我“忘记”1 个文本框时,我收到“INSERT INTO 语句中的语法错误”。 如何避免这种情况?

string commandPerson = "Insert into Person (LastName,FirstName,DateOfBirth,Phone,Email,AdditionalInfo, Hobbies, CVinDropBOX, Informationrequest) values('" + txtLastN.Text + "','" + txtFirstN.Text + "'," + txtDOB.Text + ",'" + txtPhone.Text + "','" + txtEmail.Text + "','" + txtAdditionalInfo.Text + "','" + txtHobbies.Text + "'," + chkCVDROPBOX.Checked + "," + chkInformation.Checked + ")";

当每个文本框都有一个值时,没有问题。 只有当我将 1 或 2 个文本框留空时,错误消息才会显示: INSERT INTO 语句中的语法错误

【问题讨论】:

  • 这里没有水晶球,所以如果你不显示任何代码,没人知道你在做什么。

标签: c# .net asp.net oledb oledbcommand


【解决方案1】:

使用参数化方法,它不仅可以安全地防止 SQL 注入,而且还可以让您解决问题,因为您将在未提供参数值时将其设置为 NULL(或 string.empty)。

这里是一个例子:

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

这里是完整的文章:http://www.mikesdotnetting.com/Article/26/Parameter-Queries-in-ASP.NET-with-MS-Access

【讨论】:

    【解决方案2】:

    为 dob 试试这个(你缺少单引号):

     '" + txtDOB.Text + "'. 
    

    【讨论】:

    • 试试这个像 ('" +Convert.ToDateTime(txtDOB.Text).toString() + "')
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-04-06
    • 1970-01-01
    • 2014-02-07
    相关资源
    最近更新 更多