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
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
I am trying to save checked items from a checkedlistbox to my SQL database and i am filling my checkedlistbox from the same SQL database,So far i am able to get the text of checked item from the checkedlistbox and i saved it in a string then i used a label to display if i am getting the text of checked item or not and its working but when i try to insert the checked data in database i get a error "Connection property has not been initialized." on ExecuteNonQuery() method.
Imports System.Data
Imports System.Data.SqlClient
Public Class Form1
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim da As New SqlDataAdapter
Dim dt As New DataTable
Dim connectionString As String = "Server=DESKTOP-V12PTAV ;Database=test ;User Id=sa ;Password=wills8877"
Using conn As New SqlConnection(connectionString)
conn.ConnectionString = connectionString
conn.Open()
Dim str As String
str = "Select sem1 From sem"
da = New SqlDataAdapter(str, conn)
dt = New DataTable
da.Fill(dt)
CheckedListBox1.DataSource = dt
CheckedListBox1.DisplayMember = "sem1"
conn.Close()
End Using
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim str As String
Dim cmd As New SqlCommand
Dim sql As String
Dim connectionString As String = "Server=DESKTOP-V12PTAV ;Database=test ;User Id=sa ;Password=wills8877"
Using conn As New SqlConnection(connectionString)
conn.Open()
Dim itemChecked As Object
For Each itemChecked In CheckedListBox1.CheckedItems
str = itemChecked.item("sem1").ToString
Label1.Text = str
sql = "insert into pretab(pre) values('" + str + "')"
cmd.ExecuteNonQuery()
Next
conn.Close()
End Using
End Sub
End Class
This error
The problem maybe arised from your query syntax. Try this:
sql = "insert into pretab(pre) values(#str)"
cmd.Parameters.AddWithValue("#str", str)
cmd.ExecuteNonQuery()
OOPS.. I just realised that you forgot to assign your command with connection. So, please try to add the following statement:
cmd = New SqlCommand(sql, conn)
befor execution your command. So the final code should look like this:
sql = "insert into pretab(pre) values(#str)"
cmd = New SqlCommand(sql, conn)
cmd.Parameters.AddWithValue("#str", str)
cmd.ExecuteNonQuery()
First off I would do data operations in a class e.g. (note I focus on inserts). You need to change server and catalog to your server and catalog on SQL-Server.
Imports System.Data.SqlClient
Public Class Operations
Private Server As String = "KARENS-PC"
Private Catalog As String = "CheckedListBoxDatabase"
Private ConnectionString As String = ""
Public Sub New()
ConnectionString = $"Data Source={Server};Initial Catalog={Catalog};Integrated Security=True"
End Sub
Public Function Read() As DataTable
' read rows for checked listbox here
End Function
Public Sub Insert(ByVal sender As List(Of String))
Using cn As SqlConnection = New SqlConnection With {.ConnectionString = ConnectionString}
Using cmd As SqlCommand = New SqlCommand With {.Connection = cn, .CommandText = "insert into pretab(pre) values (#pre)"}
cmd.Parameters.Add(New SqlParameter With {.ParameterName = "#pre", .SqlDbType = SqlDbType.NVarChar})
cn.Open()
For Each item In sender
cmd.Parameters("#pre").Value = item
cmd.ExecuteNonQuery()
Next
End Using
End Using
End Sub
End Class
Form code
Public Class Form1
Private ops As New Operations
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim Result = CheckedListBox1.Items.OfType(Of String).Where(Function(item, index) CheckedListBox1.GetItemChecked(index)).ToList
ops.Insert(Result)
End Sub
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
CheckedListBox1.DataSource = ops.Read
CheckedListBox1.DisplayMember = "sem1"
End Sub
End Class
It appears that you did not provide the connection to the command. Your code was button click
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim str As String
Dim cmd As New SqlCommand
Dim sql As String
Dim connectionString As String = "Server=DESKTOP-V12PTAV ;Database=test ;User Id=sa ;Password=wills8877"
Using conn As New SqlConnection(connectionString)
conn.Open()
Dim itemChecked As Object
For Each itemChecked In CheckedListBox1.CheckedItems
str = itemChecked.item("sem1").ToString
Label1.Text = str
sql = "insert into pretab(pre) values('" + str + "')"
cmd.ExecuteNonQuery()
Next
conn.Close()
End Using
End Sub
What you need to do is before cmd.ExecuteNonQuery() you need to provide it a connection cmd.connection = connectionString
this will remove the cmd.ExecuteNonQuery() error.
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
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.
I'm using a Windows form application in Visual Basic 2012 to create a new Microsoft Access database using .ADOX. I can create the database but can't create a table in the database.
My code is :
Imports ADOX
Imports System.Data.OleDb
Public Class Form1
Dim mycommand As OleDbCommand
Dim myconnection As OleDbConnection
Dim myReader As OleDbDataReader
Dim str As String
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim cat As New Catalog()
Dim tablename As String = "Users"
cat.Create("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=F:\important\DDL.mdb;Jet OLEDB:Engine Type=5")
cat = Nothing
myconnection = New OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=F:\important\DDL.mdb ")
myconnection.Open()
str = "CREATE TABLE [ " & tablename & "] ([Username] varchar(50)), ([Password] varchar(50)), ([E-mail] varchar(75))"
mycommand = New OleDb.OleDbCommand(str, myconnection)
mycommand.ExecuteNonQuery()
MsgBox("Database created")
End Sub
End Class
The error is get is:
An unhandled exception of type 'System.Data.OleDb.OleDbException' occurred in System.Data.dll
Additional information: Syntax error in CREATE TABLE statement.
Any help is appreciated.
EDITED:
The following code gets past the first error but i now get a field definition error, i know the code should work as it works with adding a number field, possible because the field type in access is short text and long text but anything i've tried doesn't seem to work.
Imports ADOX
Imports System.Data.OleDb
Public Class Form1
Dim mycommand As OleDbCommand
Dim myconnection As OleDbConnection
Dim myReader As OleDbDataReader
Dim str As String
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim cat As New Catalog()
cat.Create("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=F:\important\DDL.mdb;Jet OLEDB:Engine Type=5")
cat = Nothing
myconnection = New OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=F:\important\DDL.mdb ")
myconnection.Open()
str = "CREATE TABLE [Users] (Username Varchar(50), Password Varchar(50), E-mail Varchar(50))"
mycommand = New OleDb.OleDbCommand(str, myconnection)
mycommand.ExecuteNonQuery()
MsgBox("Database created")
End Sub
End Class
Looks like you have too many parenthesizes, but I think the actual error is coming from the leading space you have in your query:
V
str = "CREATE TABLE [ " & tablename & "]
Try changing it to:
str = "CREATE TABLE [" & tablename & "] ([Username] varchar(50), [Password] varchar(50), [E-mail] varchar(75))"
Make sure you dispose of your objects, preferably in a using block:
Example:
Using cn As New OleDb.OleDbConnection(mdb)
cn.Open()
Using cmd As New OleDb.OleDbCommand(str, cn)
cmd.ExecuteNonQuery()
End Using
End Using
At the end the code looks like this:
Imports ADOX
Imports System.Data.OleDb
Public Class Form1
Dim mycommand As OleDbCommand
Dim myconnection As OleDbConnection
Dim myReader As OleDbDataReader
Dim str As String
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim cat As New Catalog()
cat.Create("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Test\DDL.mdb;Jet OLEDB:Engine Type=5")
cat = Nothing
Using myconnection As New OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Test\DDL.mdb ")
myconnection.Open()
str = "CREATE TABLE [Users] ([Username] varchar(50), [Password] varchar(50), [E-mail] varchar(50))"
Using mycommand As New OleDb.OleDbCommand(str, myconnection)
mycommand.ExecuteNonQuery()
End Using
End Using
MsgBox("Database created")
End Sub
End Class