简体   繁体   中英

Syntax error in INSERT INTO statement for MS Access

I have a SQL Insert Into command that works in normal conditions. That means if I fill in every textbox, the data is send to the db (Acces db).

But when I 'forget' 1 textbox, I receive a "Syntax error in INSERT INTO statement." How can you avoid this?

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 + ")";

When every textbox has a value, there is no problem. It is only when i leave 1 or 2 textboxes empty, the error message shows : Syntax error in INSERT INTO statement

use a parametrized approach which not only is safe against SQL Injection, but also let's you solve your problem because you will set a parameter value to NULL (or string.empty) when not provided.

here an example:

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

and here the full article: http://www.mikesdotnetting.com/Article/26/Parameter-Queries-in-ASP.NET-with-MS-Access

尝试这个dob(你错过了单引号):

 '" + txtDOB.Text + "'. 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM