Click here to Skip to main content
15,889,116 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
C#
using System.Windows.Forms;
namespace Database_Access
{
    public class Connection
    {
        OleDbConnection oldb;
        OleDbCommand command;
        public Connection()
        {
            oldb = new OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=F:\\abc.mdb;");
            //command = oldb.CreateCommand();
        }
        public void insert_query(String user_id, String user_password)
        {
            try
            {
                oldb.Open();
                String sql = "INSERT INTO info(ID,Password) values(" + user_id + "," + user_password + ")";
                command = new OleDbCommand(sql, oldb);
              /*  command.CommandText = "INSERT INTO info(ID,Password) values('" + user_id + "','" + user_password + "')";
                command.CommandType = CommandType.Text;*/

                command.ExecuteNonQuery();
                MessageBox.Show("Insert Successfully");

            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            finally
            {
                oldb.Close();
            }
        }
    }
}

When I run this code, it shows syntax error in insert into statement.
How do I solve this?
Posted
Updated 22-Dec-13 6:51am
v3
Comments
Mike Meinz 22-Dec-13 14:36pm    
Use parameterized SQL commands to prevent SQL Injection Attacks.
See Giving SQL Injection the Respect it Deserves

1 solution

The commented SQL is closer to what you want, although you should really avoid string concatenation in favor of using parameters, look up SQL injection attacks.

C#
String sql = "INSERT INTO info(ID,Password) values('" + user_id + "','" + user_password + "')";


Notice the ' in the command? They surround string values.

Also, make sure that you are using ID as your User ID in your table, a lot of people name the primary key ID which is usually an integer.
 
Share this answer
 
Comments
Kawshik_itbd 22-Dec-13 11:58am    
it always show syntex error :(
Ron Beyer 22-Dec-13 15:04pm    
Did you try copy/pasting the query into Access QueryBuilder to see what error it gives there? It may be more descriptive. You also may have to surround your table/column names in square brackets, like:

"INSERT INTO [info] ([ID], [Password]) values ('" + user_id + "','" + user_password + "')"

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900