error in Inserting data in database - vb.net

Problem : Inserting data into database.
Error:
SQLException was unhandled by the user
Incorrect Syntax near the keyword 'User'
the one the I put arrow is the line that is highlighted seems it was the error i'm not sure.
Imports System.Web
Imports System.Web.UI
Imports System.Web.UI.WebControls
Imports System.Data.SqlClient
Imports System.Configuration
Partial Public Class _Default
Inherits System.Web.UI.Page
Dim con As New SqlConnection(ConfigurationManager.ConnectionStrings("ConnectionString").ConnectionString)
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
con.Open()
End Sub
Protected Sub addBTN_Click(ByVal sender As Object, ByVal e As EventArgs) Handles addBTN.Click
Dim cmd As New SqlCommand("insert into User (Name, Gender, Age) values ('" & nameTB.Text & "', '" & genderTB.Text & "', '" & ageTB.Text & "')", con)
cmd.ExecuteNonQuery() <------------------------------
con.Close()
nameTB.Text = ""
genderTB.Text = ""
ageTB.Text = ""
End Sub
End Class

User is a reserved word so needs to be in square brackets. Your query is open to SQL injection so needs to be parameterized. I would advise opening the connection just before you need it. Also use the Using statement will take care of closing and disposal for you.
Using con As New SqlConnection(ConfigurationManager.ConnectionStrings("ConnectionString").ConnectionString)
Using cmd As New SqlCommand("insert into [User] (Name, Gender, Age) values (#nameTB, #genderTB,#ageTB)", con)
cmd.Parameters.AddWithValue("#nameTB", nameTB.Text)
cmd.Parameters.AddWithValue("#genderTB", genderTB.Text)
cmd.Parameters.AddWithValue("#ageTB", ageTB.Text)
cmd.CommandType = CommandType.Text
con.Open()
cmd.ExecuteNonQuery()
nameTB.Text = ""
genderTB.Text = ""
ageTB.Text = ""
End Using
End Using

User is a reserved word. Enclose the word with square brackets:
Dim cmd As New SqlCommand("insert into [User] (Name, Gender, Age) values ('" & nameTB.Text & "', '" & genderTB.Text & "', '" & ageTB.Text & "')", con)
Source: https://stackoverflow.com/a/6082422/1271037

Related

Oracle INSERT on VB.net Null reference exception

Please help i am a newbie on oracle database i am used on using mysql and i really don't have any idea how can i debug my code. Here is my code.
Imports System.Diagnostics
Imports Oracle.DataAccess.Client
Imports Oracle.DataAccess.Types
Public Class mainMenu
Dim conn As New OracleConnection
Private cmd As OracleCommand
Private da As OracleDataAdapter
Private cb As OracleCommandBuilder
Private ds As DataSet
Private Sub mainMenu_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
AddHandler txtProductName.TextChanged, AddressOf ValidateInputs
AddHandler txtQty.TextChanged, AddressOf ValidateInputs
AddHandler txtPrice.TextChanged, AddressOf ValidateInputs
conn.ConnectionString = "User Id=antonina" & _
";Password=antonina" & _
";Data Source=xe"
Try
conn.Open()
Catch ex As Exception
MessageBox.Show(ex.Message.ToString())
Finally
conn.Dispose()
End Try
End Sub
Private Sub ValidateInputs(ByVal Sender As Object, ByVal e As EventArgs)
Button1.Enabled = Not (txtProductName.Text = String.Empty OrElse txtQty.Text = String.Empty OrElse txtPrice.Text = String.Empty)
End Sub
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim productName As String
Dim qty As Integer
Dim price As Integer
Dim cat As String
productName = txtProductName.Text
qty = Integer.Parse(txtQty.Text)
price = Integer.Parse(txtPrice.Text)
cat = cmbCat.Text
conn = New OracleConnection("User Id=antonina;Password=antonina;Data Source=xe")
da = New OracleDataAdapter()
Try
da.InsertCommand = New OracleCommand("INSERT INTO INVENTORY(INVENTORY_PRODUCTNAME,INVENTORY_CAT,INVENTORY_QTY,INVENTORY_PRICE) VALUES ('" & productName & "'," & qty & "," & price & ",'" & cat & "')", conn)
Debug.WriteLine("Success")
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
End Class
When i click my add button it says object reference not set to an instance of an object. I know i might just have a stupid syntax error. Please help me.
I am sure that all my variables have a value. also i am using oracle 10g
I have never seen that somebody uses a OracleDataAdapter in order to insert anything to database, usually OracleDataAdapter is used to retrieve data from database, i.e. a SELECT ... command or a function call which gets a RefCursor.
Perhaps InsertCommand, resp. UpdateCommand and DeleteCommand are used to modify data of OracleDataAdapter after it has been filled from your database - I do not know, I never used it. These command are called with method OracleDataAdapter.Update(da)
Anyway, usually you would do it like this:
Dim cmd As OracleCommand
cmd = New OracleCommand("INSERT INTO INVENTORY (INVENTORY_PRODUCTNAME,INVENTORY_QTY,INVENTORY_PRICE,INVENTORY_CAT) VALUES (:productName, :qty, :price, :cat)", conn)
cmd.CommandType = CommandType.Text
cmd.Parameters.Add("productName", OracleDbType.Varchar2, ParameterDirection.Input).Value = productName
cmd.Parameters.Add("qty", OracleDbType.Int32, ParameterDirection.Input).Value = qty
cmd.Parameters.Add("price", OracleDbType.Int32, ParameterDirection.Input).Value = price
cmd.Parameters.Add("cat", OracleDbType.Varchar2, ParameterDirection.Input).Value = cat
cmd.ExecuteNonQuery()
Note the order of columns, see your code:
INVENTORY_PRODUCTNAME, INVENTORY_CAT, INVENTORY_QTY, INVENTORY_PRICE
('" & productName & "'," & qty & "," & price & ",'" & cat & "')"
I assume da is for DataAdapter. You need first instantiate your dataadapter by call its constructor.
conn = new OracleConnection(yourConnectionString)
da = New OracleDataAdapter()
da.InsertCommand = New OracleCommand("INSERT INTO INVENTORY(INVENTORY_PRODUCTNAME,INVENTORY_CAT,INVENTORY_QTY,INVENTORY_PRICE) VALUES ('" & productName & "'," & qty & "," & price & ",'" & cat & "')", conn)
also, you missing '()' after VALUES statement in sql syntax.
Other things may help is you can move your parsing statement into try-catch element to avoid error.
hope this help.

How to do a registerform by ASP.NET VB SQL

I am designing a registerform by vb.net but I don't know how to do this.
The following is my code:
Protected Sub btnOK_Click(sender As Object, e As EventArgs) Handles btnOK.Click
Dim Conn As SqlConnection = New SqlConnection("localdb\v11.0")
Conn.Open()
Dim sqlstr As String = "insert into user_profile(username,password,nickname,realname,email) values('&username.Text&','&password.Text&','&nickname.Text&','&realname.Text&','&email.Text&')"
Dim cmd As New SqlCommand(sqlstr, Conn)
cmd.ExecuteNonQuery()
cmd.Cancel()
Conn.Close()
Conn.Dispose()
End Sub
but there is some errors...
and, is this concept right? If click the button then insert the data into SQL database?
Protected Sub btnOK_Click(sender As Object, e As EventArgs) Handles btnOK.Click
Dim Conn As SqlConnection = New SqlConnection("localdb\v11.0")
Conn.Open()
Dim sqlstr As String = "insert into user_profile(username, password, nickname, realname, email) values('" & username.Text & "','" & password.Text & "','" & nickname.Text & "','" & realname.Text & "','" & email.Text &"')"
Dim cmd As New SqlCommand(sqlstr, Conn)
cmd.ExecuteNonQuery()
cmd.Cancel()
Conn.Close()
Conn.Dispose()
End Sub
You need to build your sqlstr correctly ... use quotes to separate the string from values of text boxes. You are also open to sql injections you should use paramaterised values.

Invalid SQL statement; expected 'DELETE', 'INSERT', 'PROCEDURE', 'SELECT', or 'UPDATE'

Hi I have an invalid sql statement error. This is my code:
Imports System.Data.OleDb 'For OleDbConnection 
Imports System.Data 'For ConnectionState 
Public Class WebForm1
Inherits System.Web.UI.Page
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
End Sub
Protected Sub btnInsert_Click(sender As Object, e As EventArgs) Handles btnInsert.Click
'1 declare the variables
Dim strName As String = txtName.Text
Dim strAddress As String = txtAddress.Text
'2. creates a new connection to your DB.
Dim conn As New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source='C:\Users\GT\Documents\Database11.accdb'")
If conn.State = ConnectionState.Open Then
conn.Close()
End If
'3. open the connection to your DB. 
conn.Open()
'4. assign your SQL statement into sqlString variable. 
Dim sqlString As String
sqlString = "INSERT INTO tblStuInfo (stuName, stuAddress) VALUES ('" & strName & "' , '" & strAddress & "')"
'5. create a new command that links your SQL statement with your connection. 
Dim sqlcommand As New OleDbCommand(sqlString, conn)
'6. execute your command.
sqlcommand.ExecuteNonQuery()
End Sub
End Class
What is the problem? The path of the database and the table name of the DB is correct. Please help!
try to replace
sqlString = "INSERT INTO tblStuInfo (stuName, stuAddress) VALUES ('"
& strName & "' , '" & strAddress & "')"
with
sqlString = "INSERT INTO tblStuInfo (stuName, stuAddress) VALUES ('"
& strName.Replace("'", "''") & "' , '" & strAddress.Replace("'", "''") & "')"
this should solve any SQL injection issue, that happen when your string contain the ' character.
Anyway, I think you should add (or use) a key in the underlying table, otherwise how are you going to get these values back?

VB2010 database insert query throwing exception error

I am a new user to VB.net ( of 2 weeks ) and coming from a php background, am finding it tough going. I have created a small form that should insert some data into an access mdb database. However, I keep getting an error of:
System.Data.OleDb.OleDbException
I have outlined in my pasted code where this error is occurring and would be grateful if someone could point out where I have gone wrong. many thanks.
Imports System.Data.OleDb
Public Class frmMain
Dim strConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\domain\storage1.mdb"
Dim cnnOLEDB As New OleDbConnection(strConnectionString)
Dim cmdOLEDB As New OleDbCommand
Dim cmdInsert As New OleDbCommand
Dim cmdUpdate As New OleDbCommand
Dim cmdDelete As New OleDbCommand
Dim cmd As OleDbCommand
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
End Sub
Private Sub btnInsert_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnInsert.Click
Dim first, last As String
Dim age As Integer
first = txtFirstName.Text
last = txtLastName.Text
age = txtAge.Text
Dim InsertQuery As String
InsertQuery = "INSERT INTO Details (first,last,age) VALUES ('" & first & "','" & last & "','" & age & "')"
cnnOLEDB.Open()
Dim cmd As OleDbCommand = New OleDbCommand(InsertQuery, cnnOLEDB)
cmd.Parameters.AddWithValue("first", txtFirstName.Text)
cmd.Parameters.AddWithValue("last", txtLastName.Text)
cmd.Parameters.AddWithValue("age", txtAge.Text)
cmd.ExecuteNonQuery() <--- ERROR
cnnOLEDB.Close()
MessageBox.Show("Insert complete.")
End Sub
End Class
The problem is here:
InsertQuery = "INSERT INTO Details (first,last,age) VALUES ('" & first & "','" & last & "','" & age & "')"
cmd.Parameters.AddWithValue("first", txtFirstName.Text)
cmd.Parameters.AddWithValue("last", txtLastName.Text)
cmd.Parameters.AddWithValue("age", txtAge.Text)
Try this:
InsertQuery = "INSERT INTO Details (first,last,age) VALUES (#first, #last, #age)"
Then for the Parameters:
cmd.Parameters.AddWithValue("#first", txtFirstName.Text)
cmd.Parameters.AddWithValue("#last", txtLastName.Text)
cmd.Parameters.AddWithValue("#age", txtAge.Text)
You can then remove these lines as you don't need them:
Dim first, last As String
Dim age As Integer
first = txtFirstName.Text
last = txtLastName.Text
age = txtAge.Text
First and Last are reserved words for Jet 4.0. They should not be used as column names. Access itself will let you get away with it, SQL code is a little less forgiving. If you can't avoid using those words, try putting them in square brackets [first] when addressing them. For more information on reserved words, see http://support.microsoft.com/kb/248738.

Syntax Error in Insert Statement

I'm new to Database connection and when I am having a problem with the cmdInsert.ExecuteNonQuery() line it says there is a syntax error with the INSERT INTO statement and I can't figure out what the problem is:
Imports System.Data
Imports System.Data.OleDb
Public Class txtNotes
Dim cnnOLEDB As New OleDbConnection
Dim cmdInsert As New OleDbCommand
Dim strConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & System.Environment.CurrentDirectory & "\CourseworkDB"
'the name of the database goes in here'
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
cnnOLEDB.ConnectionString = strConnectionString
cnnOLEDB.Open()
End Sub
Private Sub AddFirstName_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles AddFirstName.Click
If txtFirstName.Text <> "" Then
MsgBox(cmdInsert.CommandText)
cmdInsert.CommandText = "INSERT INTO Customer (First Name) VALUES (" & txtFirstName.Text & ", '"
cmdInsert.CommandType = CommandType.Text
cmdInsert.Connection = cnnOLEDB
cmdInsert.ExecuteNonQuery()
Else
MsgBox("Enter the required values:" & vbNewLine & "1. First Name")
End If
cmdInsert.Dispose()
End Sub
End Class
I Strongly suggest not getting into a routine of building SQL strings by concatinating strings together. You are leaving yourself wide open to SQL-Injection, especially if this is web based. You should build your commands with place-holder parameters in the string, then add the parameters to the command object. Add the parameters in the same sequence as they would appear in the command... such as
cmdInsert.CommandText = "INSERT INTO Customer (FirstName, LastName) VALUES ( #parmFirstName, #parmLastName )"
cmdInsert.Parameters.AddWithValue( "#parmFirstName", txtFirstName.Text );
cmdInsert.Parameters.AddWithValue( "#parmLastName", txtLastName.Text );
If your field names have embedded spaces, different databases work
differently, some requires single backtick (the key left of the number
1) around the field. such as 'first name'. Some use square brackets,
such as [first name].
Try this
"INSERT INTO Customer (First Name) VALUES ('" & txtFirstName.Text & "')"
Warning: Bobby is watching you.
cmdInsert.CommandText = _
"INSERT INTO Customer (First Name) VALUES ('" & txtFirstName.Text & "')"