VB.NET SQL ACCESS Insert Statement - sql

net and i'm trying to insert data into access database using sql, i have the code below, when i try to execute, it prompts me an error message and highlighting con.open() i don't understand why it's not working, can anyone guide me. Thank
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles AddBut.Click
Dim dbProvider = "Provider=Microsoft.ACE.OLEDB.12.0; Data Source= c:\Databse\Company_db.accdb"
Dim dbSource = "Data Source= C:\Databse\Company_db.accdb"
Dim empNum As String
Dim empFname As String
Dim empLname As String
Dim empDept As String
Dim empStat As String
Dim empYears As String
empNum = eNumText.Text
empFname = empFnameText.Text
empLname = empLnameText.Text
empDept = Deptd.Text
empStat = Statd.Text
empYears = yearstext.Text
Dim sql = "INSERT INTO tbl_empinfo (EmpID, FirstName, LastName, Department, Status, Years " & _
") " & _
"Values(empNum, empFname, empLname, empDept, empStat, empYears)"
con.ConnectionString = dbProvider & dbSource
Using cmd = New OleDb.OleDbCommand(sql, con)
con.Open()
cmd.Parameters.AddWithValue("EmpID", empNum)
cmd.Parameters.AddWithValue("FirstName", empFname)
cmd.Parameters.AddWithValue("LastName", empLname)
cmd.Parameters.AddWithValue("Department", empDept)
cmd.Parameters.AddWithValue("Status", empStat)
cmd.Parameters.AddWithValue("Years", empYears)
cmd.ExecuteNonQuery()
End Using
con.Close()
End Sub

Standard problem, when you see a Syntax error in an otherwise fine SQL statement, look for RESERVED KEYWORDS for the underlying database.
In your case the word POSITION is a reserved keyword for MS-ACCESS.
Put it between square brackets
Dim sql = "INSERT INTO tbl_empinfo (EmpID, FirstName, LastName, Department, " & _
"[Position], Status, Years) " & _
"Values(empNum, empFname, empLname, empDept, empStat, empYears)"
However, you have another error in that query. You have 7 fields to insert but you pass only 6 parameters, missing just the parameter for the POSITION field.
You need to fix also the connection string. You write
con.ConnectionString = dbProvider & dbSource
but this result in an invalid file name
"Provider=Microsoft.ACE.OLEDB.12.0; Data Source=
c:\Databse\Company_db.accdbData Source= C:\Databse\Company_db.accdb"
(line splitted for readability)

I consider that you have initialized the object of "OleDbConnection".
Try to get the Connection String from the Property window of your database (From Server Explorer Window right click on your database select properties option).
And when you are opening the connection use following code:
If con.State = ConnectionState.Closed Then
con.Open()
End If
Hope it helps you.

Related

select case and error join multiple table

Imports System.Data.OleDb
Public Class Form1
Dim conn As OleDbConnection
Dim cmd As OleDbCommand
Dim da As OleDbDataAdapter
Dim strSQL As String
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles btnsearch.Click
Dim fieldselect As String = ""
Select Case ComboBox1.Text
Case "startYear"
fieldselect = "startYear"
Case "genres"
fieldselect = "genres"
Case "Rating"
fieldselect = "Rating"
End Select
conn = New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=Movies.accdb; Persist Security Info=False;")
strSQL = "SELECT startYear, genres, averageRating FROM (basic.tconst Inner JOIN Rating.tconst on basic.tconst=Rating.tconst)" & fieldselect & "'" & TextBox1.Text & "%'"
conn.Open()
da = New OleDbDataAdapter(strSQL, conn)
Dim ds As New DataSet("Movies")
da.Fill(ds, "Movies")
DataGridView1.DataSource = ds.Tables("Movies")
conn.Close()
End Sub
Keep you data objects local so you can control there closing and disposing. Using...End Using blocks do this for you even it there is an error.
Are all your fields in the Select Case the same datatype? If not you will have to adjust the code. If you need help, tell me the datatypes so I can fix the code.
Always use parameters to avoid sql injection. A text box can hold a Drop Table command. Parameters are treated as values not executable code.
If you need to update later in the code, you will need to have a primary key available in your Select.
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
'Since your field name exactly matches the combo text the Case statement is not necessary
Dim fieldselect As String = ComboBox1.Text
Dim dt As New DataTable
Using conn = New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=Movies.accdb; Persist Security Info=False;")
Dim strSQL = "SELECT startYear, genres, averageRating FROM basic.tconst Inner JOIN Rating.tconst on basic.tconst=Rating.tconst Where " & fieldselect & " = #FieldValue;"
Using cmd As New OleDbCommand(strSQL, conn)
cmd.Parameters.Add("#FieldValue", OleDbType.VarChar).Value = TextBox1.Text
conn.Open()
dt.Load(cmd.ExecuteReader)
End Using
End Using
DataGridView1.DataSource = dt
End Sub
i wanted to use combo box as the filter for my program, i need to filter data from 2 different table. rating has it own table and basic is different table. both of the field mention above does not have any connection.
It's a bit had to help without context but I gave it a try :
I would replace
strSQL = "SELECT startYear, genres, averageRating FROM (basic.tconst Inner JOIN Rating.tconst on basic.tconst=Rating.tconst)" & fieldselect & "'" & TextBox1.Text & "%'"
With
"SELECT startYear, genres, averageRating " &
"FROM basic.tconst " &
"INNER JOIN Rating.tconst on basic.tconst=Rating.tconst " & fieldselect & "'" & TextBox1.Text & "%'"
To get better help, could you explain how tables Rating and basic works and what fieldselect is ?

Selecting specific table from database VB

Public Sub UserList_SelectedIn(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles UserList.SelectedIndexChanged
Dim provider As String
Dim dataFile As String
Dim connString As String
Dim myConnection As OleDbConnection = New OleDbConnection
provider = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source ="
dataFile = "\users.accdb"
connString = provider & dataFile
myConnection.ConnectionString = connString
myConnection.Open()
Chart1.Series.Add("Score") 'Adds the graph into the program
Dim cmdd As OleDbCommand = New OleDbCommand("SELECT [Score], [Month] FROM * WHERE Table ='" & UserList.SelectedItem, myConnection)
Dim dr2 As OleDbDataReader = cmdd.ExecuteReader
While dr2.Read
Chart1.Series("Score").Points.AddXY(dr2("Month").ToString, dr2("Score").ToString) 'Adds the month/score to the graph
End While
End Sub
Trying to find a way to make the following line of code allow me to select data from a specific table that the user can choose from a listbox.
Dim cmdd As OleDbCommand = New OleDbCommand("SELECT [Score] FROM * WHERE Table ='" & UserList.SelectedItem, myConnection)
It gives the error when running: Syntax error in FROM clause.
I'm guessing it's because of the * after FROM.
This should be a comment but I need 50+ rep to comment... but it should show you how to structure your query
SELECT [column] FROM [table] WHERE [condition]
I was just about to add comment to say you need another " ' " at the end of the command, but also, I've never seen FROM * used in a command like that. Not saying it's wrong, I just have never seen it :). Anyways, this should help out with the issue, dont forget to bracket tables and fields if they contain wildcards or spaces in the names. Brackets can be used even if do not contain spaces or wildcards.
Public Sub UserList_SelectedIn(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles UserList.SelectedIndexChanged
Dim provider As String
Dim dataFile As String
Dim connString As String
Dim myConnection As OleDbConnection = New OleDbConnection
provider = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source ="
dataFile = "\users.accdb"
connString = provider & dataFile
myConnection.ConnectionString = connString
myConnection.Open()
Chart1.Series.Add("Score") 'Adds the graph into the program
Dim Table_Str As String = "[" & UserList.SelectedItem & "]"
Dim cmdd As OleDbCommand = New OleDbCommand("SELECT [Score], [Month] FROM " & Table_Str, myConnection)
Dim dr2 As OleDbDataReader = cmdd.ExecuteReader
While dr2.Read
Chart1.Series("Score").Points.AddXY(dr2("Month").ToString, dr2("Score").ToString) 'Adds the month/score to the graph
End While
End Sub
You can also add in If statements or error checking before running the code to make sure a selection has been made from the user.
Hth
Chicken
Turning on Option Strict will force you to use .ToString .SelectedItem is an object and Option Strict requires an explicit conversion. Not too many extra keystrokes but it could save your runtime errors.
Dim cmdd As OleDbCommand = New OleDbCommand("SELECT [Score], [Month] FROM [" & ListBox1.SelectedItem.ToString & "]", myConnection)
Laziness will do you no good. You should try to write all the table names after the FROM clause. Maybe that will solve it.

OleDb Error unknown field name “Name” in visual basics

Hey there are many question like this however i didn't find the right one. i keep on getting this error,
image
i am Using
vb.net and Ms-access database.
I have researched and didn't get anything, i checked the name "productID" and it is correct. So i dont know what wrong? Please help
My Code:
Private Sub btnAdd_Click(sender As Object, e As EventArgs) Handles btnAdd.Click
Dim dbProvider As String
Dim dbSource As String
Dim MyDocumentsFolder As String
Dim TheDatabase As String
Dim FullDatabasePath As String
Dim Sql As String
Dim con As New OleDb.OleDbConnection
Dim empty = Me.Controls.OfType(Of TextBox)().Where(Function(txt) txt.Text.Length = 0)
If empty.Any Then
MessageBox.Show("Please fill all informations")
Else
dbProvider = "PROVIDER=Microsoft.Jet.OLEDB.4.0;"
TheDatabase = "C:\Users\jacob\Desktop\MS Office\project.mdb"
MyDocumentsFolder = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments)
FullDatabasePath = MyDocumentsFolder & TheDatabase
dbSource = "Data Source = " & TheDatabase
con.ConnectionString = dbProvider & dbSource
Sql = "INSERT INTO tblUsers (productID, quantity, price, productSection, supplierID) VALUES (#ProductID, #Quantity, #Price, #ProductSection, #SupplierID)"
MessageBox.Show("Database is now open")
con.Open()
Dim command As New OleDb.OleDbCommand(Sql, con)
command.Parameters.Add("#ProductID", OleDb.OleDbType.VarChar).Value = txtProductName.Text
command.Parameters.Add("#Quantity", OleDb.OleDbType.Integer).Value = txtQuantity.Text
command.Parameters.Add("#Price", OleDb.OleDbType.Currency).Value = txtPrice.Text
command.Parameters.Add("#ProductSection", OleDb.OleDbType.VarChar).Value = txtSection.Text
command.Parameters.Add("#SupplierID", OleDb.OleDbType.VarChar).Value = txtSupplier.Text
command.ExecuteNonQuery()
MessageBox.Show("Product Added Successfully")
con.Close()
MessageBox.Show("Database is now Closed")
End If
End Sub
The error is shown in this line : command.ExecuteNonQuery()
SQL is case sensitive, check if something is capitalized in your Sql variable and not capitalized in your table in SQL server or vise versa.
you can also check if the capitalization on the parameters might be causing the issue as well.

Error on .ExecuteNonQuery() in SQL Update Query [duplicate]

This question already has an answer here:
ADD SQL QUERY STAT
(1 answer)
Closed 8 years ago.
I'm trying to update an Access database using a SQL query, whenever I click the save button, it generates an error
An unhandled exception of type 'System.Data.OleDb.OleDbException' occurred in System.Data.dll
Additional information: No value given for one or more required parameters.
And highlights .ExecuteNonQuery(). Can you guys help me on this? I'm new to vb.net.
Thanks in advance.
Private Sub SaveButton_Click(sender As Object, e As EventArgs) Handles SaveButton.Click
Dim empNum As String
Dim empFname As String
Dim empLname As String
Dim empDept As String
Dim empStat As String
Dim empYears As String
empNum = eNumText.Text
empFname = empFnameText.Text
empLname = empLnameText.Text
empDept = DeptText.Text
empStat = StatText.Text
empYears = yearstext.Text
con.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0; Data Source= c:\Databse\Company_db.accdb"
con.Open()
MsgBox(empNum)
Dim SqlAdapter As New OleDbDataAdapter
Dim Table As New DataTable
Dim sqlQuery As String = "UPDATE tbl_empinfo SET EmpID='" & empNum & "', FirstName ='" & empFname & "', LastName='" & empLname & "', Department='" & empDept & "', Status='" & empStat & "', Years='" & empYears & "' WHERE EmpID ='" & empNum & "' "
Using cmd As New OleDbCommand(sqlQuery, con)
With cmd
.CommandText = sqlQuery
.Connection = con
.Parameters.AddWithValue("EmpID", empNum)
.Parameters.AddWithValue("FirstName", empFname)
.Parameters.AddWithValue("LastName", empLname)
.Parameters.AddWithValue("Department", empDept)
.Parameters.AddWithValue("Status", empStat)
.Parameters.AddWithValue("Years", empYears)
.ExecuteNonQuery()
End With
End Using
sqlQuery = "SELECT * FROM tbl_empinfo "
Dim cmd1 As New OleDbCommand
Dim da As New OleDbDataAdapter
With cmd1
.CommandText = sqlQuery
.Connection = con
With SqlAdapter
.SelectCommand = cmd1
.Fill(Table)
End With
With DataGridView1
.DataSource = Table
End With
End With
con.Close()
End Sub
your query syntax is wrong. Since you are using params, use placeholders in the SQL: (the question marks are not some 'etc' type thing, you use ? to mark parameters!):
Dim sqlQuery As String = "UPDATE tbl_empinfo SET FirstName = ?,
LastName=?, Department=?,
Status=?, Years=? WHERE empID = ?"
Note: Six parameters
' USING will dispose of the cmd when it is done with it
' ...can also set the SQL and connection props in the constructor:
Using cmd As New OleDbCommand(sqlQuery, con)
With cmd
' no reason to move Textboxes to a variable either:
.Parameters.AddWithValue("#p1", empFnameText.Text)
.Parameters.AddWithValue("#p2", empLnameText.Text)
.Parameters.AddWithValue("#p3", DeptText.Text)
.Parameters.AddWithValue("#p4", StatText.Text)
.Parameters.AddWithValue("#p5", yearstext.Text)
your missing 6th parameter:
.Parameters.AddWithValue("#p6", eNumText.Text)
.ExecuteNonQuery()
End With
End Using
I dont think Access supports named params, so you use dummy ones but be sure to AddWithValue in the order specified in the SQL string.
EDIT
You can just create a SQL string with the values embedded instead of using params which is sort of what your SQL string does. Params are much better (research SQL injection attacks), but your string method is wrong (and you cant mix methods). It should be:
Dim sqlQuery As String = "UPDATE tbl_empinfo " &
"SET FirstName = " & empFname & ", LastName=" & empLname
The variables have to be outside the quotes or you will be setting FirstName to the literal "empFname"

Getting Data MS Access then Placing it inside VBNET texbox

i'm trying to figure out what's wrong with my code,
I'm trying to extract the value of employe ID selected from a dropdown, then get all information of that employee and place it in a textbox vb.net form, but there's a error whenever i select an employee ID
it's giving me an error message of : "An unhandled exception of type 'System.Data.OleDb.OleDbException' occurred in System.Data.dll
Additional information: No value given for one or more required parameters."
Thus highlighting reader, i'm not sure what's the problem, i have initialized the reader... Please guide me. Thanks
Private Sub eNumText_SelectedIndexChanged(sender As Object, e As EventArgs) Handles eNumText.SelectedIndexChanged
Dim dbSource = "Data Source= C:\Databse\Company_db.accdb"
con.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0; Data Source= c:\Databse\Company_db.accdb"
Dim sqlQuery As String
Dim sqlCommand As New OleDbCommand
Dim sqlAdapter As New OleDbDataAdapter
Dim Table As New DataTable
Dim empNum As String
Dim empFname As String
Dim empLname As String
Dim empDept As String
Dim empStat As String
Dim empYears As String
empNum = eNumText.Text
empFname = empFnameText.Text
empLname = empLnameText.Text
empDept = DeptText.Text
empStat = StatText.Text
empYears = yearstext.Text
sqlQuery = "SELECT * FROM tbl_empinfo WHERE EmpID like empNum"
With sqlCommand
.CommandText = sqlQuery
.Connection = con
.Parameters.AddWithValue("EmpID", empNum)
With sqlAdapter
.SelectCommand = sqlCommand
.Fill(Table)
End With
With DataGridView1
.DataSource = Table
End With
End With
Dim path = "Data Source= C:\Databse\Company_db.accdb"
Dim command = "SELECT * FROM tbl_empinfo WHERE EmpID like empNum"
QueryData(path, Command)
con.Close()
End Sub
Private Sub QueryData(PathDb As String, command As String)
PathDb = "Data Source= C:\Databse\Company_db.accdb"
Using connection As New System.Data.OleDb.OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & PathDb)
Using da As New System.Data.OleDb.OleDbCommand(command, con)
con.Open()
Dim reader = da.ExecuteReader()
If reader.Read() Then
empFnameText.Text = reader("FirstName")
empLnameText.Text = reader("LastName")
End If
con.Close()
End Using
End Using
End Sub
You need to prefix your parameter empNum with an #: #empNum. See this answer: How to pass a parameter from vb.net for an example.