Click here to Skip to main content
15,900,511 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hai All,
I am developing VB Application in VS2010. When i read the data base by using select and display it on Datagrid view , here i didn't get any problem. But when i insert the new record into that database have an error...
Here is my code for insert new record...
SQL
cmdInsert.CommandText = "INSERT INTO Alarm (Alarm, Date,Time) VALUES ('" & al & "', '" & dt & "', '" & tm & "')"
            MsgBox(cmdInsert.CommandText)
            cmdInsert.CommandType = CommandType.Text
            cmdInsert.Connection = cnnOLEDB
            cmdInsert.ExecuteNonQuery()
            cmdInsert.Dispose()

dt,tm and al are strings

error is occur at runtime just like INSERT INTO Statement error
Posted

Ensure that the type of values you are storing into the tables and the type that you are passing into the query are correct. Alarm may be an int (number) type and not string.
 
Share this answer
 
v2
Comments
Himachandra 3-Jan-12 3:53am    
Conformly Alarm is text type
Himachandra 4-Jan-12 0:37am    
Thank U Abhinav S
VALUES ('" & al & "', '" & dt & "', '" & tm & "')"

Try This ''''

dim S= "(" & chr(34) & al & Chr(34) & "," & chr(34) & dt & Chr(34) & "," & chr(34) & tm & Chr(34) & ")"


Values & S
 
Share this answer
 
v2
Comments
Himachandra 4-Jan-12 0:37am    
Thank U Tom Moody
Never concatenate actual values to the SQL statement. Instead use OleDbParameter[^].

So your code could look something like:
VB
cmdInsert.CommandText = "INSERT INTO Alarm (Alarm, Date,Time) VALUES (?, ?, ?)"
MsgBox(cmdInsert.CommandText)
cmdInsert.CommandType = CommandType.Text
cmdInsert.Connection = cnnOLEDB
cmdInsert.Parameters.AddWithValue("@alarm", al);
cmdInsert.Parameters.AddWithValue("@date", dt);
cmdInsert.Parameters.AddWithValue("@time", tm);
cmdInsert.ExecuteNonQuery()
cmdInsert.Dispose()

That would help you against conversion problems and SQL injections.

Also don't use string data for dates or times. Instead use the native data types. As you're having both date and time separately, I'd suggest that you define only one field in the table and the data type would be datetime2. See: http://msdn.microsoft.com/en-us/library/bb677335.aspx[^]
 
Share this answer
 
Comments
Himachandra 4-Jan-12 0:37am    
Thank U Mika Wendelius
Wendelius 4-Jan-12 1:24am    
You're welcome :)

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