Click here to Skip to main content
15,891,431 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
C#
Try
       Dim con As New OleDbConnection
       Dim cmd As New OleDbCommand
       Dim ddt As New OleDbDataAdapter
       Dim dtd As New DataSet
       con.ConnectionString = ("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=D:\Ticket.mdb")
       cmd.CommandText = "INSERT INTO user VALUES('" & TextBox1.Text & "' , '" & TextBox2.Text & "')"
       cmd.Connection = con
       con.Open()
       cmd.ExecuteNonQuery()
       MessageBox.Show("New User Created", "New User", MessageBoxButtons.OK, MessageBoxIcon.Information)
   Catch
       MsgBox("User Already Created")
   End Try


What I have tried:

Nothing....Just getting this error again and again.....my code seems to be right
Posted

When you omit the column names make sure you insert the data in the column order of the table, better still use the column names in the statement :
SQL INSERT INTO Statement[^]
 
Share this answer
 
As explained in Number of query values and destination fields are not the same.[^] you need to specify the target columns. Otherwise you will have problems when columns are changed, added, or the order changes.

Another potential error source is the fact that you're not using parameters. If the data in the text box has an apostrophe (') then your statement will fail. Not to mention the problems for the fact that you're vulnerable to SQL injections. So make use of OleDbParameter Class (System.Data.OleDb)[^]

As a side note when you catch the exception, you assume that the exception happened because the record already exists. This is just one of many potential reasons for the statement to fail. So the best option would be to show the real message for the exception. I really suggest going through Properly executing database operations[^]
 
Share this answer
 
v2

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