i'm programing in vs 2010 a vb.net project.
don't know what is happening when i insert the data because it gives this message:
A first chance exception of type 'System.Data.SqlClient.SqlException' occurred in System.Data.dll
what's wrong?
here is the part of the code that makes it
Imports System.Data
Imports System.Data.SqlClient
Public Class atl
Dim myconnection As SqlConnection
Dim mycommand As SqlCommand
Dim myConnectionString As String = "Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\uss.mdf;Integrated Security=True;User Instance=True"
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs) Handles Button2.Click
myconnection = New SqlConnection(myConnectionString)
mycommand = New SqlCommand("insert into atl([nome],[morada],[sexo],[datan],[telf],[desporto]) values ('" & txtNome.Text & "','" & txtMorada.Text & _
"','" & ComboSexo.Text & "','" & CType(txtDataN.Text, DateTime).ToString("yyy-MM-dd") & "','" & txtTelemovel.Text & "','" & ComboBox1.Text & "')", myconnection)
myconnection.Open()
Try
mycommand.ExecuteNonQuery()
Label1.Content = "O atleta " + txtNome.Text + " foi registado!!!"
Catch ex As Exception
Label1.Content = "Falhou a ligação a base de dados!!!"
End Try
End Sub
does some of your values contains single quote? your statement is vulnerable with sql injecton. why don't you use sql parameters?
Dim myConnectionString As String = "Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\uss.mdf;Integrated Security=True;User Instance=True"
Dim sqlStatement = "insert into atl([nome],[morada],[sexo],[datan],[telf],[desporto]) "
sqlStatement &= "VALUES (#nome, #morada, #sexo, #datan, #telf, #desporto)"
Using xConn As New SqlConnection(myConnectionString)
Try
Dim xComm As New SqlCommand(sqlStatement, xConn)
With xComm
.CommandType = CommandType.Text
.Parameters.AddWithValue("#nome", txtNome.Text)
.Parameters.AddWithValue("#morada", txtMorada.Text)
.Parameters.AddWithValue("#sexo", ComboSexo.Text)
.Parameters.AddWithValue("#datan", CType(txtDataN.Text, DateTime).ToString("yyyy-MM-dd") )
.Parameters.AddWithValue("#telf", txtTelemovel.Text)
.Parameters.AddWithValue("#desporto", ComboBox1.Text)
End With
xConn.Open()
xComm.ExecuteNonQuery()
xComm.Dispose()
Catch ex As SqlException
MsgBox (ex.Message)
End Try
End Using
also you have a mistake here: CType(txtDataN.Text, DateTime).ToString("yyy-MM-dd") it should yyyy-MM-dd not yyy-MM-dd
Related
This question already has an answer here:
Syntax error in INSERT INTO Statement when writing to Access
(1 answer)
Closed 7 years ago.
I'm using Microsoft Visual Studio 2013 and im trying to make a registration form for my account database using VB.NET. This is my code so far:
Private Sub btnRegistery_Click(sender As Object, e As EventArgs) Handles btnRegistery.Click
Dim usernme, passwrd As String
usernme = txtUsernm.Text
passwrd = txtpasswrd.Text
Dim myconnection As OleDbConnection
Dim constring As String = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\hasan\Documents\Visual Studio 2012\Projects\hasan\Login_Info.accdb"
myconnection = New OleDbConnection(constring)
myconnection.Open()
Dim sqlQry As String
sqlQry = "INSERT INTO tbl_user(username, password) VALUES(usernme , passwrd)"
Dim cmd As New OleDbCommand(sqlQry, myconnection)
cmd.ExecuteNonQuery()
End Sub
The code compiles fine, but when i try to register any new information i get the following message:
A first chance exception of type 'System.Data.OleDb.OleDbException'
occurred in System.Data.dll
Additional information: Syntax error in INSERT INTO statement.
If there is a handler for this exception, the program may be safely continued.
What could be a solution and cause for this problem?
Your query seems wrong: ... VALUES(usernme, passwrd)... --
Here the usernmeand passwrd are not variables for database, but just plain text in the query.
Use parameters, like this:
Dim usernme, passwrd As String
usernme = txtUsernm.Text
passwrd = txtpasswrd.Text
Dim constring As String = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\hasan\Documents\Visual Studio 2012\Projects\hasan\Login_Info.accdb"
Using myconnection As New OleDbConnection(constring)
myconnection.Open()
Dim sqlQry As String = "INSERT INTO [tbl_user] ([username], [password]) VALUES (#usernme, #passwrd)"
Using cmd As New OleDbCommand(sqlQry, myconnection)
cmd.Parameters.AddWithValue("#usernme", usernme)
cmd.Parameters.AddWithValue("#passwrd", passwrd)
cmd.ExecuteNonQuery()
End using
End using
You aren't including the actual variable information missing the quotations, like
VALUES ('" & usernme & '", ...etc
You should be using parameters to avoid errors and sql injection:
sqlQry = "INSERT INTO tbl_user (username, password) VALUES(#usernme, #passwrd)"
Dim cmd As New OleDbCommand(sqlQry, myconnection)
cmd.Parameters.AddWithValue("#usernme", usernme)
cmd.Parameters.AddWithValue("#passwrd", passwrd)
cmd.ExecuteNonQuery()
Dim cnn As New OleDb.OleDbConnection
Private Sub RefreshData()
If Not cnn.State = ConnectionState.Open Then
'-------------open connection-----------
cnn.Open()
End If
Dim da As New OleDb.OleDbDataAdapter("select stdID as [StdIdTxt]," &
"Fname as [FnameTxt] ,Lname,BDy,age,gender,address,email,LNO,MNO,course" &
"from studentTB order by stdID", cnn)
Dim dt As New DataTable
'------------fill data to data table------------
da.Fill(dt)
'close connection
cnn.Close()
End Sub
Private Sub AddNewBtn_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles AddNewBtn.Click
Dim cmd As New OleDb.OleDbCommand
'--------------open connection if not yet open---------------
If Not cnn.State = ConnectionState.Open Then
cnn.Open()
End If
cmd.Connection = cnn
'----------------add data to student table------------------
cmd.CommandText = "insert into studentTB (stdID,Fname,Lname,BDy,age,gender,address,email,LNO,MNO,course)" &
"values (" & Me.StdIdTxt.Text & "','" & Me.FnameTxt.Text & "','" & Me.LNameTxt.Text & "','" &
Me.BdyTxt.Text & "','" & Me.AgeTxt.Text & "','" & Me.GenderTxt.Text & "','" &
Me.AddTxt.Text & "','" & Me.EmailTxt.Text & "','" & Me.Hometxt.Text & "','" & Me.mobileTxt.Text & "','" & Me.Coursetxt.Text & "')"
cmd.ExecuteNonQuery()
'---------refresh data in list----------------
'RefreshData()
'-------------close connection---------------------
cnn.Close()
This insert error is nothing but a syntax error, there is no need for changing your code. please avoid reserved words like "password" form your database. This error is due to the field name password
The SQL string should look like this
sqlQry = "INSERT INTO tbl_user(username, password) VALUES(" & usernme & "', " & passwrd & ")"
The values usernme & passwrd aren't valid to the database.
Beyond that you really should look into using a Command object and parameters.
I am trying to insert textbox text into a database using VISUAL STUDIO here is my code:
Dim usernme, passwrd As String
usernme = REG_USER_USERNAME.Text
passwrd = REG_USER_PASSWORD.Text
Dim constring As String = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=E:\Login.accdb"
myConnection.Open()
Dim sqlQry As String = "INSERT INTO Admins (USERNAME, PASSWORD) VALUES('" & usernme & "','" & passwrd & "')"
MsgBox(sqlQry)
Dim cmd As OleDbCommand = New OleDbCommand(sqlQry, myConnection)
cmd.ExecuteNonQuery()
myConnection.Close()
But i get an exception error including this:
Additional information: Syntax error in INSERT INTO statement.
Whats wrong with my code, i have quotation marks round the values too!
The direct answer is that Password is a reserved word in Access. Thus:
Dim sqlQry As String = "INSERT INTO Admins (USERNAME, [PASSWORD]) VALUES('" & usernme & "','" & passwrd & "')"
That said, as you do a direct concatenation with non-sanitised user input, do follow the advices posted by #Plutonix.
You could try it this way.
*Imports System.Data.OleDb
Public Class Form1
Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
' Requires: Imports System.Data.OleDb
' ensures the connection is closed and disposed
Using connection As New OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;" & _
"Data Source=""C:\your_path_here\InsertInto.mdb"";" & _
"Persist Security Info=False")
' open connection
connection.Open()
' Create command
Dim insertCommand As New OleDbCommand( _
"INSERT INTO Table1([inputOne] , [inputTwo] , [inputThree]) " & _
"VALUES (#inputOne, #inputTwo, #inputThree);", _
connection)
' Add the parameters with value
insertCommand.Parameters.AddWithValue("#inputOne", TextBox1.Text)
insertCommand.Parameters.AddWithValue("#inputTwo", TextBox2.Text)
insertCommand.Parameters.AddWithValue("#inputThree", TextBox3.Text)
' you should always use parameterized queries to avoid SQL Injection
' execute the command
insertCommand.ExecuteNonQuery()
MessageBox.Show("Insert is done!!")
End Using
End Sub
End Class*
I have a readini file to connect to my SQL Server table, and in my query code to display data from it, I'm getting an error that I've not been able to solve, is there anybody here who can?
This is the error:
Error 1
Overload resolution failed because no accessible 'New' can be called with these arguments:
'Public Sub New(selectCommandText As String, selectConnection As System.Data.OleDb.OleDbConnection)': Value of type 'SQLServerApplication.readini' cannot be converted to 'System.Data.OleDb.OleDbConnection'.
'Public Sub New(selectCommandText As String, selectConnectionString As String)': Value of type 'SQLServerApplication.readini' cannot be converted to 'String'.
This is the code:
Imports System.Data.OleDb
Imports System.Data.SqlClient
Public Class frmViewDtb
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim connection As readini = New readini()
connection.getConnectionString()
Dim sql As String = "SELECT * FROM tblPerson"
Dim da As New OleDbDataAdapter(sql, connection)
Dim ds As New DataSet()
da.Fill(ds, "tblPerson")
DataGridView1.DataSource = ds
DataGridView1.DataMember = "tblPerson"
End Sub
End Class
The line that the error is occurring on is line 13:
Dim da As New OleDbDataAdapter(sql, connection)
Code for getConnectionString;
Public Function getConnectionString() As String
Dim s As String =
"Provider=" & provider & ";" &
"user ID=" & username & ";" &
"password=" & password & ";" &
"initial catalog=" & databasename & ";" &
"data source=" & servername & "; " &
"Persists Security Info=False"
End Function
Thanks in advance if you can get it!
I believe you are getting the error as the constructor for OleDbDataAdpater is expecting two strings and your connection variable isn't a string. I suspect your code needs to look like this:
Dim connection As readini = New readini()
Dim ConnString = connection.getConnectionString()
Dim sql As String = "SELECT * FROM tblPerson"
Dim da As New OleDbDataAdapter(sql, ConnString)
Dim ds As New DataSet()
da.Fill(ds, "tblPerson")
DataGridView1.DataSource = ds
DataGridView1.DataMember = "tblPerson"
The getConnectionString method also needed amending to add the Return statement:
Public Function getConnectionString() As String
Dim s As String =
"Provider=" & provider & ";" &
"user ID=" & username & ";" &
"password=" & password & ";" &
"initial catalog=" & databasename & ";" &
"data source=" & servername & "; " &
"Persists Security Info=False"
Return s
End Function
When I try to insert data in these three field gets an error saying error in INSERT INTO Statement.
but when a save in only the first field sname it gets added but when adds other two gets this error
I am getting an exception in INSERT INTO Statement check below
any advice?
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Try
Dim dbprovider As String = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\Taher\Documents\Visual Studio 2010\Projects\WindowsApplication1\WindowsApplication1\Database1.accdb;Persist Security Info=False;"
Me.con = New OleDb.OleDbConnection()
con.ConnectionString = dbprovider
con.Open()
Dim sqlquery As String = "INSERT INTO admin (sname,username,password)" + "VALUES ('" & txtname.Text & "','" & txtuser.Text & "','" & txtpass.Text & "');"
Dim sqlcommand As New OleDb.OleDbCommand(sqlquery)
With sqlcommand
.CommandText = sqlquery
.Connection = con
.ExecuteNonQuery()
con.Close()
End With
MsgBox("User Registered")
Catch ex As Exception
MsgBox(ex.ToString)
End Try
End Sub
The word PASSWORD is a reserved keyword in JET-SQL for Microsoft Access. If you have a column with that name you should encapsulate it with square brackets
"INSERT INTO admin (sname,username,[password])" &% _
"VALUES ('" & txtname.Text & "','" & txtuser.Text & _
"','" & txtpass.Text & "');"
That's the reason of the syntax error, however let me tell you that building sql commands concatenating strings is a very bad practice. You will have problems when your values contain single quotes and worst of all, your code could be used for sql injection Attacks
So your code should be changed in this way
Dim sqlquery As String = "INSERT INTO admin (sname,username,password)" & _
"VALUES (?, ?, ?)"
Dim sqlcommand As New OleDb.OleDbCommand(sqlquery)
With sqlcommand
.CommandText = sqlquery
.Connection = con
.Parameters.AddWithValue("#p1", txtname.Text)
.Parameters.AddWithValue("#p2", txtuser.Text)
.Parameters.AddWithValue("#p3", txtpass.Text)
.ExecuteNonQuery()
con.Close()
End With
also your use of the object OleDbConnection doesn't follow a good pattern. In case of exception you don't close the connection and this could be a problem in reusing the connection in subsequent calls.
You should try to use the Using statement
Using connection = New OleDb.OleDbConnection()
connection.ConnectionString = dbprovider
connection.Open()
.....
' rest of command code here '
' No need to close the connection
End Using
in this way, also if you get an exception the OleDbConnection will be closed and disposed without impact on system resource usage.
In the form load event, I connect to the SQL Server database:
Private Sub AddBook_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
myConnection = New SqlConnection("server=.\SQLEXPRESS;uid=sa;pwd=123;database=CIEDC")
myConnection.Open()
End Sub
Here in the Insert event, I use the following code:
Private Sub cmdAdd_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdAdd.Click
Try
myConnection.Open()
myCommand = New SqlCommand("INSERT INTO tblBook(BookCode, BookTitle, Author, PublishingYear, Price, EnterDate, CatID, RackID, Amount) VALUES('" & txtBookCode.Text & "','" & txtTitle.Text & "','" & txtAuthor.Text & "','" & txtPublishYear.Text & "','" & txtPrice.Text & "', #" & txtEnterDate.Text & "#, " & txtCategory.Text & "," & txtRack.Text & "," & txtAmount.Text & ")")
myCommand.ExecuteNonQuery()
MsgBox("The book named '" & txtTitle.Text & "' has been inseted successfully")
ClearBox()
Catch ex As Exception
MsgBox(ex.Message())
End Try
myConnection.Close()
End Sub
And It produces the following error:
ExecuteNonQuery: Connection property has not been initialized
Connection Assignment - You aren't setting the connection property of the SQLCommand. You can do this without adding a line of code. This is the cause of your error.
myCommand = New SqlCommand("INSERT INTO tblBook(BookCode, BookTitle, Author, PublishingYear, Price, EnterDate, CatID, RackID, Amount) VALUES('" & txtBookCode.Text & "','" & txtTitle.Text & "','" & txtAuthor.Text & "','" & txtPublishYear.Text & "','" & txtPrice.Text & "', #" & txtEnterDate.Text & "#, " & txtCategory.Text & "," & txtRack.Text & "," & txtAmount.Text & ")", MyConnection)
Connection Handling - You also need to remove `MyConnection.Open' from your Load Handler. Just open it and close it in your Click Handler, as you are currently doing. This is not causing the error.
Parameterized SQL - You need to utilize SQL Parameters, despite the fact that you are not using a Stored Procedure. This is not the cause of your error. As Conrad reminded me, your original code dumps values straight from the user into a SQL Statement. Malicious users will steal your data unless you use SQL Parameters.
Dim CMD As New SqlCommand("Select * from MyTable where BookID = #BookID")
CMD.Parameters.Add("#BookID", SqlDbType.Int).Value = CInt(TXT_BookdID.Text)
You need to set the Connection property on the command:
myCommand.Connection = myConnection
Pretty much what the error message implies - the Connection property of the SqlCommand object hasn't been assigned to the connection you opened (in this case you called it myConnection).
Also, a word of advice here. Do some reading on sql parameters - doing sql concatenation from user input without any sanity checks is the way SQL injection attacks happen.
This is one way to do it:
Private Sub cmdAdd_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdAdd.Click
Try
myConnection.Open()
myCommand = New SqlCommand( _
"INSERT INTO tblBook(BookCode, BookTitle, Author, PublishingYear, Price, " & _
" EnterDate, CatID, RackID, Amount) " & _
"VALUES(#bookCode, #bookTitle, #author, #publishingYear, #price, #enterDate, " & _
" #catId, #rackId, #amount)")
myCommand.Connection = myConnection
with myCommand.Parameters
.AddWithValue("bookCode", txtBookCode.Text)
.AddWithValue("bookTitle", txtTitle.Text)
.AddWithValue("author", txtAuthor.Text)
.AddWithValue("publishingYear", txtPublishYear.Text)
.AddWithValue("price", txtPrice.Text)
.AddWithValue("enterDate", txtEnterDate.Text)
.AddWithValue("catId", txtCategory.Text)
.AddWithValue("rackId", txtRack.Text)
.AddWithValue("amount", txtAmount.Text)
end with
myCommand.ExecuteNonQuery()
MsgBox("The book named '" & txtTitle.Text & "' has been inseted successfully")
ClearBox()
Catch ex As Exception
MsgBox(ex.Message())
End Try
myConnection.Close()
End Sub
Module Module1
Public con As System.Data.SqlClient.SqlConnection
Public com As System.Data.SqlClient.SqlCommand
Public ds As System.Data.SqlClient.SqlDataReader
Dim sqlstr As String
Public Sub main()
con = New SqlConnection("Data Source=.....;Initial Catalog=.....;Integrated Security=True;")
con.Open()
frmopen.Show()
'sqlstr = "select * from name1"
'com = New SqlCommand(sqlstr, con)
Try
com.ExecuteNonQuery()
'MsgBox("success", MsgBoxStyle.Information)
Catch ex As Exception
MsgBox(ex.Message())
End Try
'con.Close()
'MsgBox("ok", MsgBoxStyle.Information, )
End Sub
End Module
Please try to wrap the use of your connections (including just opening) inside a USING block. Assuming the use of web.config for connection strings:
Dim connection As New SqlConnection(ConfigurationManager.ConnectionStrings("web.config_connectionstring").ConnectionString)
Dim query As New String = "select * from Table1"
Dim command as New SqlCommand(query, connection)
Using connection
connection.Open()
command.ExecuteNonQuery()
End Using
And PARAMETERIZE anything user-entered.. please!