Imports System.Data.OleDb
Public Class Money_Donated
Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
All_Donations.Show()
Me.Close()
provider = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source ="
dataFile = "C:\Users\Derick\Desktop\ICE 9\Donors.accdb"
End Sub
Dim provider As String
Dim dataFile As String
Dim connString As String
Public dr As OleDbDataReader
Private Sub Button2_Click(sender As System.Object, e As System.EventArgs) Handles Button2.Click
Dim myConnection As OleDbConnection = New OleDbConnection()
myConnection.ConnectionString = connString
connString = provider & dataFile
TextBox1.Clear()
myConnection.Open()
Dim str As String
str = "SELECT * FROM Donors WHERE (Code = '" & Donators121.Amount_of_money_donatedTextBox.Text & "')"
Dim cmd As OleDbCommand = New OleDbCommand(str, myConnection)
dr = cmd.ExecuteReader
myConnection.Close()
While dr.Read()
TextBox1.Text = dr("Description").ToString
End While
End Sub
End Class
It looks like you are setting the connection string with an empty string. You need to swap the line connString = provider & dataFile with the line myConnection.ConnectionString = connString. Otherwise, you are setting the connection string of the connection object to an empty string.
Dim myConnection As OleDbConnection = New OleDbConnection()
connString = provider & dataFile
myConnection.ConnectionString = connString
TextBox1.Clear()
Also, as OneFineDay suggests you should use parameters rather than creating SQL strings as your code is currently vulnerable to SQL injection attacks.
Related
I want to set a variable to a value in an Access Database table from aspx.vb. I want to return the highest "PalletNumber" to txbPalletNumber textbox. What am I doing wrong?
Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
Dim conn As New OleDbConnection
Dim connString As String
Dim cmd As New OleDbCommand
Try
' Set the connection string.
connString = "Provider=Microsoft.ACE.OLEDB.12.0;Data
Source=C:\Users\SF7\Desktop\Shore Fresh Logistics_be_be.accdb"
' Open the connection.
conn.ConnectionString = connString
conn.Open()
'Set the command properties.
cmd.Connection = conn
cmd.CommandText = "SELECT PalletNumber, MAX(PalletNumber) FROM
tblPalletNumber"
txbPalletNumber.Text = cmd.ExecuteScalar()
conn.Close()
GridView1.DataBind()
Catch ex As Exception
'Error handling
End Try
txbPackday.Text = DateAndTime.Now
End Sub
Here is the solution. Thanks for all the help.
Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
Dim conn As New OleDbConnection
Dim connString As String
Dim test As String
' Set the connection string.
connString = "Provider=Microsoft.ACE.OLEDB.12.0;DataSource=C:\Users\SF7\Desktop\Shore Fresh Logistics_be_be.accdb"
' Open the connection.
conn.ConnectionString = connString
conn.Open()
Dim cmd As New OleDbCommand
'Set the command properties.
cmd.Connection = conn
cmd.CommandText = "SELECT MAX(PalletNumber) FROM tblPalletNumber"
test = cmd.ExecuteScalar()
txbPalletNumber.Text = cmd.ExecuteScalar()
conn.Close()
GridView1.DataBind()
txbPackday.Text = DateAndTime.Now
End Sub
So I have created a database and want to insert information from my form in VB to the database. I have linked and coded it however, I keep getting this error message: Syntax error in INSERT INTO Statement . I have looked at many other similar questions however none of the solutions work. Here is my code:
Imports System.Data.OleDb
Class Form1
Dim Provider As String
Dim DataFile As String
Dim ConnString As String
Dim MyConnection As OleDbConnection = New OleDbConnection
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
End Sub
Private Sub btnSave_Click(sender As Object, e As EventArgs) Handles btnSave.Click
Provider = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source= "
DataFile = "C:\Users\Documents\Visual Studio 2012\Projects\DatabaseTest\DatabaseTest\Database.accdb"
ConnString = Provider & DataFile
MyConnection.ConnectionString = ConnString
MyConnection.Open()
Dim Strng As String
Strng = "INSERT INTO [Table1]([StudentName], [StudentScore] Values (?,?))"
Dim Cmmnd As OleDbCommand = New OleDbCommand(Strng, MyConnection)
Cmmnd.Parameters.Add(New OleDbParameter("StudentName", CType(txtName.Text, String)))
Cmmnd.Parameters.Add(New OleDbParameter("StudentScore", CType(txtScore.Text, String)))
Try
Cmmnd.ExecuteNonQuery()
Cmmnd.Dispose()
MyConnection.Close()
txtName.Clear()
txtScore.Clear()
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
End Class
Any help would be much appreciated!!
End brace in the wrong place. You also do not need to convert the Text property to a string in the parameters.
Imports System.Data.OleDb
Class Form1
Dim Provider As String
Dim DataFile As String
Dim ConnString As String
Dim MyConnection As OleDbConnection = New OleDbConnection
Private Sub btnSave_Click(sender As Object, e As EventArgs) Handles btnSave.Click
Provider = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source= "
DataFile = "C:\Users\Documents\Visual Studio 2012\Projects\DatabaseTest\DatabaseTest\Database.accdb"
ConnString = Provider & DataFile
MyConnection.ConnectionString = ConnString
MyConnection.Open()
Dim Strng As String
Strng = "INSERT INTO [Table1]([StudentName], [StudentScore]) Values (?,?)"
Dim Cmmnd As OleDbCommand = New OleDbCommand(Strng, MyConnection)
Cmmnd.Parameters.Add(New OleDbParameter("StudentName", txtName.Text))
Cmmnd.Parameters.Add(New OleDbParameter("StudentScore", txtScore.Text))
Try
Cmmnd.ExecuteNonQuery()
Cmmnd.Dispose()
MyConnection.Close()
txtName.Clear()
txtScore.Clear()
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
End Class
I am having an issue when I am setting up this Register form.
My current code is this:
Public Class Form2
Dim con As New OleDb.OleDbConnection
Dim dbProvider As String
Dim dbSource As String
Dim MyDocumentsFolder As String
Dim TheDatabase As String
Dim FullDatabasePath As String
Dim ds As New DataSet
Dim da As OleDb.OleDbDataAdapter
Dim sql As String
Dim DBTest1 As String
Dim DBTestP1 As String
Dim cmd As New OleDbCommand(sql, con)
Dim connStr As String
Public Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim connection As New OleDb.OleDbConnection(connStr)
dbProvider = "Provider=Microsoft.ACE.OLEDB.12.0;"
TheDatabase = "\Robocopy_Test.accdb"
MyDocumentsFolder = "C:\Users\Dan\Desktop\WindowsApplication2"
FullDatabasePath = MyDocumentsFolder & TheDatabase
dbSource = "Data Source = C:\Users\Dan\Desktop\WindowsApplication2\Robocopy_Testaccdb1.accdb"
con.ConnectionString = dbProvider & dbSource
con.Open()
sql = "SELECT * FROM Robocopy"
da = New OleDb.OleDbDataAdapter(sql, con)
'da.Fill(ds, "Robocopy")
MessageBox.Show("Databse is Open")
DBTest1 = DBTest.Text
DBTestP1 = DBTestP.Text
'DBTest.Text = ds.Tables("Robocopy").Rows(0).Item(1)
'DBTestP.Text = ds.Tables("Robocopy").Rows(0).Item(2
sql = "INSERT INTO Robocopy(username,password) VALUES('" & DBTest1 & "','" & DBTestP1 & "')"
cmd.Connection = connection
connection.Open()
cmd.CommandText = sql
da.InsertCommand = cmd
da.InsertCommand.ExecuteNonQuery()
connection.Close()
'With cmd.Parameters
'.AddWithValue("usernamer", DBTest.Text)
'.AddWithValue("password", DBTestP.Text)
'.AddWithValue("email", txtsub.text)
'.AddWithValue("contactnum", txtau.text)
'End With
'cmd.ExecuteNonQuery()
End Sub
Public Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
con.Close()
MessageBox.Show("Database Is now Closed")
End Sub
End Class
I am having the issue at connection.open(). The error that I am having is
The ConnectionString property has not been initialized.
I have been trying for the past hour to find different ways to write to the database but to no prevail and I cannot figure this out.
[In response to Steve
My code after editing and still the same error
Imports System.Data.OleDb
Public Class Form2
Dim connection As New OleDb.OleDbConnection
Dim dbProvider As String
Dim dbSource As String
Dim MyDocumentsFolder As String
Dim TheDatabase As String
Dim FullDatabasePath As String
Dim ds As New DataSet
Dim da As OleDb.OleDbDataAdapter
Dim sql As String
Dim DBTest1 As String
Dim DBTestP1 As String
Dim cmd As New OleDbCommand(sql, connection)
Dim connStr As String
Public Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim connection As New OleDb.OleDbConnection(connStr)
dbProvider = "Provider=Microsoft.ACE.OLEDB.12.0;"
TheDatabase = "\Robocopy_Test.accdb"
MyDocumentsFolder = "C:\Users\Dan\Desktop\WindowsApplication2"
FullDatabasePath = MyDocumentsFolder & TheDatabase
dbSource = "Data Source = C:\Users\Dan\Desktop\WindowsApplication2\Robocopy_Testaccdb1.accdb"
Me.connection.ConnectionString = dbProvider & dbSource
Me.connection.Open()
sql = "SELECT * FROM Robocopy"
da = New OleDb.OleDbDataAdapter(sql, connection)
'da.Fill(ds, "Robocopy")
MessageBox.Show("Databse is Open")
DBTest1 = DBTest.Text
DBTestP1 = DBTestP.Text
'DBTest.Text = ds.Tables("Robocopy").Rows(0).Item(1)
'DBTestP.Text = ds.Tables("Robocopy").Rows(0).Item(2
sql = "INSERT INTO Robocopy(username,password) VALUES('" & DBTest1 & "','" & DBTestP1 & "')"
cmd.Connection = connection
connection.Open()
cmd.CommandText = sql
da.InsertCommand = cmd
da.InsertCommand.ExecuteNonQuery()
connection.Close()
'With cmd.Parameters
'.AddWithValue("usernamer", DBTest.Text)
'.AddWithValue("password", DBTestP.Text)
'.AddWithValue("email", txtsub.text)
'.AddWithValue("contactnum", txtau.text)
'End With
'cmd.ExecuteNonQuery()
End Sub
Public Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
connection.Close()
MessageBox.Show("Database Is now Closed")
End Sub
End Class
Global variables could be very ....evil. Expecially if you name them with the same name of a local variable.
Me.connection is not the same variable connection declared as local variable inside the sub. You set the connection string on the global variable then use the local variable without any connection string
Change these two lines
Me.connection.ConnectionString = dbProvider & dbSource
Me.connection.Open()
removing the Me.
connection.ConnectionString = dbProvider & dbSource
connection.Open()
and don't open the connection two times.
In any case, you don't need the adapter at all to execute an insert command
Public Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
dbProvider = "Provider=Microsoft.ACE.OLEDB.12.0;"
dbSource = "Data Source = C:\Users\Dan\Desktop\WindowsApplication2\Robocopy_Testaccdb1.accdb"
Dim connStr = dbProvider & dbSource
DBTest1 = DBTest.Text
DBTestP1 = DBTestP.Text
sql = "INSERT INTO Robocopy(username,[password]) VALUES('" & DBTest1 & "','" & DBTestP1 & "')"
Using connection = New OleDb.OleDbConnection(connStr)
Using cmd = new OleDb.OleDbCommand(sql, connection )
connection.Open()
cmd.ExecuteNonQuery()
'With cmd.Parameters
'.AddWithValue("usernamer", DBTest.Text)
'.AddWithValue("password", DBTestP.Text)
'.AddWithValue("email", txtsub.text)
'.AddWithValue("contactnum", txtau.text)
'End With
'cmd.ExecuteNonQuery()
End Using
End Using
End Sub
I see also that you have commented out the Parameterized approach to your query. Please do yourself a favour and restore as soon as possible the parameters logic. It is a lot more safe and avoids numerous errors
Finally Password is a reserved keyword in Access.Use square brakets around it otherwise you will see an unexplicable "Syntax Error" in your insert command
Public Class Form1
Dim provider As String
Dim datafile As String
Dim connstring As String
Public myconnection As OleDbConnection = New OleDbConnection
Public dr As OleDbDataReader
Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
provider = "Provider=Microsoft.Ace.OLEDB.12.0"
datafile = "Data Source=C:\Users\fess\Desktop\test\compress.accdb"
connstring = provider & ";" & datafile
myconnection.ConnectionString = connstring
End Sub
Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
myconnection.Open()
Dim str As String
str = "SELECT 'name' FROM test2 WHERE 'ID'='1'"
Dim cmd As OleDbCommand = New OleDbCommand(str, myconnection)
dr = cmd.ExecuteReader
TextBox1.Text = dr(str).ToString
myconnection.Close()
End Sub
End Class
Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
myconnection.Open()
Dim str As String
str = "SELECT ID from test2 where name='bry'"
Dim cmd As OleDbCommand = New OleDbCommand(str, myconnection)
dr = cmd.ExecuteReader
While dr.Read()
TextBox1.Text = dr("ID").ToString
End While
myconnection.Close()
Found my mistake after a bit of searching
This Syntax error (missing operator) in query expression 'Prod_Num ='. always shows up when I'm trying to search an item in the database. Please help me.
Imports System
Imports System.Data
Imports System.Data.OleDb
Public Class Form1
Dim con As New OleDb.OleDbConnection
Dim cmd As OleDbCommand
Dim da As OleDb.OleDbDataAdapter
Dim ds As New DataSet
Dim dt As New DataTable
Dim sql As String
Dim dbp As String
Dim dbs As String
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
dbp = "Provider = Microsoft.ACE.OLEDB.12.0;"
dbs = "Data Source=" & Application.StartupPath & "/POS.accdb"
con.ConnectionString = dbp & dbs
con.ConnectionString = dbp & dbs
con.Open()
sql = "SELECT * FROM tblInventory"
da = New OleDb.OleDbDataAdapter(sql, con)
da.Fill(dt)
dgList.DataSource = dt
txtPNum.Focus()
End Sub
Private Sub btnSearch_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSearch.Click
dt.Clear()
txtPNum.Text = ""
sql = "SELECT * FROM tblInventory WHERE Prod_Num =" & txtPNum.Text
da = New OleDb.OleDbDataAdapter(sql, con)
da.Fill(dt)
dgList.DataSource = dt
txtPName = dt.Rows(0).Item(1)
txtNOrder = dt.Rows(0).Item(2)
txtPRem = dt.Rows(0).Item(3)
txtPrice = dt.Rows(0).Item(4)
txtPNum.Focus()
End Sub
My guess is that you have problem here:
Private Sub btnSearch_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSearch.Click
dt.Clear()
txtPNum.Text = "" ' <-----------------
sql = "SELECT * FROM tblInventory WHERE Prod_Num =" & txtPNum.Text
da = New OleDb.OleDbDataAdapter(sql, con)
da.Fill(dt)
dgList.DataSource = dt
txtPName = dt.Rows(0).Item(1)
txtNOrder = dt.Rows(0).Item(2)
txtPRem = dt.Rows(0).Item(3)
txtPrice = dt.Rows(0).Item(4)
txtPNum.Focus()
End Sub
Remove this line:
txtPNum.Text = ""
Since you always clears the txtPNum textbox's text before passing it to the query.
NOTE:
Don't forget to implement it via parameterized query. This is not a good approach.
See parameterized query examples:
Example 1
Example 2
Hope it helps!
does txtPNum.Text contain any data?
Why don't you try checking that, because if it is empty your running SQL statement is "SELECT * FROM tblInventory WHERE Prod_Num =" which would raise that error.
Also if the Prod_Num column is integer, perhaps you should use int(txtPNum.Text) if that value is a string, this would also prevent SQL Injection.
In addition to the problem with txtPNum.Text that others have pointed out, I would recommend a couple of other things:
Use parameterized queries to avoid SQL Injection.
Use Using blocks with your connection, and close the connection as soon as you are done. In your Form_Load, for example, you open the connection and leave it open. That is not good practice.
Example:
Imports System
Imports System.Data
Imports System.Data.OleDb
Public Class Form1
Dim con As OleDbConnection
Dim cmd As OleDbCommand
Dim da As OleDbDataAdapter
Dim ds As New DataSet
Dim dt As New DataTable
Dim dbp As String
Dim dbs As String
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
dbp = "Provider = Microsoft.ACE.OLEDB.12.0;"
dbs = "Data Source=" & Application.StartupPath & "/POS.accdb"
Using con As OleDbConnection = New OleDbConnection(dbp & dbs)
con.Open()
da = New OleDbDataAdapter("SELECT * FROM tblInventory", con)
da.Fill(dt)
dgList.DataSource = dt
End Using
txtPNum.Focus()
End Sub
Private Sub btnSearch_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSearch.Click
dt.Clear()
Using con As OleDbConnection = New OleDbConnection(dbp & dbs)
con.Open()
da = New OleDbDataAdapter("SELECT * FROM tblInventory WHERE Prod_Num = #ProdNum", con)
da.SelectCommand.Parameters.AddWithValue("#ProdNum", txtPNum.Text)
da.Fill(dt)
dgList.DataSource = dt
End Using
txtPName = dt.Rows(0).Item(1)
txtNOrder = dt.Rows(0).Item(2)
txtPRem = dt.Rows(0).Item(3)
txtPrice = dt.Rows(0).Item(4)
txtPNum.Focus()
End Sub
I would also recommend adding some Try Catch blocks to handle errors, and you may need to convert the values you're assigning to text boxes if they're something other than String.