Question

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

Was it helpful?

Solution

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

OTHER TIPS

try this for the dob (you are missing the single quotes):

 '" + txtDOB.Text + "'. 
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top