0

I wrote a program that connects to MS Access. When I fill in the fields and add a new item to Access the program fails. The exception is "Syntax error in INSERT INTO statement"

Here is the relevant code.

****************************************************************
AdoHelper.cs
****************************************************************

using System;
using System.Collections.Generic;
using System.Text;
using System.Data;
using System.Data.OleDb;

namespace Yad2
{
    class AdoHelper
    {
        //get the connection string from the app.config file
        //Provider=Microsoft.ACE.OLEDB.12.0;Data Source=|DataDirectory|\Yad2.accdb
        static string connectionString = Properties.Settings.Default.DBConnection.ToString();

        //declare the db connection
        static OleDbConnection con = new OleDbConnection(connectionString);

        /// <summary>
        /// To Execute queries which returns result set (table / relation)
        /// </summary>
        /// <param name="query">the query string</param>
        /// <returns></returns>
        public static DataTable ExecuteDataTable(string query)
        {

            try
            {
                con.Open();
                OleDbCommand command = new OleDbCommand(query, con);
                System.Data.OleDb.OleDbDataAdapter tableAdapter = new System.Data.OleDb.OleDbDataAdapter(command);
                DataTable dt = new DataTable();
                tableAdapter.Fill(dt);
                return dt;
        }
        catch (Exception ex)
        {
            throw ex;
        }
        finally
        {
            con.Close();
        }
    }

    /// <summary>
    /// To Execute update / insert / delete queries
    /// </summary>
    /// <param name="query">the query string</param>
    public static void ExecuteNonQuery(string query)
    {
        try
        {
            con.Open();
            System.Data.OleDb.OleDbCommand command = new System.Data.OleDb.OleDbCommand(query, con);
            command.ExecuteNonQuery();
        }
        catch (Exception ex)
        {
            throw ex;
        }
        finally
        {
            con.Close();
        }
    }

    /// <summary>
    /// To Execute queries which return scalar value
    /// </summary>
    /// <param name="query">the query string</param>
    public static object ExecuteScalar(string query)
    {
        try
        {
            con.Open();
            System.Data.OleDb.OleDbCommand command = new System.Data.OleDb.OleDbCommand(query, con);  /// here is the Excaption !!!!!!!!!
            return command.ExecuteScalar();
        }
        catch
        {
            throw;
        }
        finally
        {
            con.Close();
        }
    }

}
}

****************************************************************************


****************************************************************************
DataQueries.cs
****************************************************************************
using System;
using System.Collections.Generic;
using System.Text;
using System.Data;

namespace Yad2
{
    class DataQueries
    {

        public static DataTable GetAllItems()
        {
            try
            {
                string query = "Select * from Messages";

                DataTable dt = AdoHelper.ExecuteDataTable(query);

                return dt;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }


        public static void AddNewItem(string mesNumber, string title , string mesDate , string contactMail , string mesType , string Details )
        {
            string query = "Insert into Messages values(" + mesNumber + " , '" + title + "' , '" + mesDate + "' , '" + contactMail + "' , , '" + mesType + "' , '" + Details + "')";
            AdoHelper.ExecuteNonQuery(query);
       }

        public static void DeleteDept(int mesNumber)
        {
            string query = "Delete from Item where MessageNumber=" + mesNumber;
            AdoHelper.ExecuteNonQuery(query);
        }
    }
}
***********************************************************************************************

Why does the program fail?

NotMe
  • 87,343
  • 27
  • 171
  • 245
user454563
  • 131
  • 1
  • 1
  • 4
  • "porgram"? "Accsses"? "excaption"? You should use spell-checker. – abelenky Dec 22 '10 at 18:47
  • 2
    [• **NEVER** write `throw ex;`](http://stackoverflow.com/questions/2999298/difference-between-throw-and-throw-new-exception/2999314#2999314). – SLaks Dec 22 '10 at 18:48
  • @abelenky: For some people, english is difficult. Hence the Edit button so we can help clean it up. – NotMe Dec 22 '10 at 18:53
  • @Chris: ESL authors in particular should use spell-checkers. The computer does the spelling so we don't have to. – abelenky Dec 22 '10 at 18:56

4 Answers4

4

When you put your string into the SQL, you get a invalid syntax.
This would happen if one of the strings contains a '.

You need to use parameters.

Also, your SQL contains , ,, which is invalid syntax.

SLaks
  • 868,454
  • 176
  • 1,908
  • 1,964
4

Try this

INSERT INTO table (column1, column2, ...)
VALUES ('value1', 'value2', ...)
edze
  • 2,965
  • 1
  • 23
  • 29
  • 1
    +1 I suspect this is the primary issue. All of the columns should be explicitly defined when doing an insert. Otherwise it's brittle and likely to blow up when a DDL change occurs. – NotMe Dec 22 '10 at 18:55
1
string query = "Insert into Messages values(" + mesNumber + " , '" + title + "' , '" + mesDate + "' , '" + contactMail + "' , , '" + mesType + "' , '" + Details + "')";

yields

Insert into Messages
values(
    <number> , 
    '<title>' , 
    '<mesDate>' , 
    '<contactMail>' , , 
    '<mesType>' , 
    '<Details>'
)

Notice the two commas after with a space between them. This is not valid SQL. You will also have a bad query if mesNumber is a null value in your code.

As Joe White commented with his link to XKCD #327, always sanitize your database inputs! That means that if a string is passed to your method, you must escape all single quotes.

As SLaks commented, never use throw ex;, just use throw;

Thorin
  • 626
  • 4
  • 11
  • 2
    No; just remove the `catch` block entirely. – SLaks Dec 22 '10 at 19:05
  • 1
    How right you are, SLaks, I never realized we could leave out the `catch` block. For those interested, here is what Microsoft says about it: "There are three possible forms of try statements: A try block followed by one or more catch blocks. **A try block followed by a finally block.** A try block followed by one or more catch blocks followed by a finally block." source: http://msdn.microsoft.com/en-us/library/aa664733(v=vs.71).aspx – Thorin Dec 22 '10 at 19:24
0

Why don't you simply print out the value of query (to the debug window, console, message box, log file... wherever!), in AddNewItem, then examine the message. It really should become clear then.

abelenky
  • 63,815
  • 23
  • 109
  • 159