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
try this for the dob (you are missing the single quotes):
'" + txtDOB.Text + "'.
精彩评论