OleDB INSERT STATEMENT Error - vb.net

I'm working on a project where I'm going to add records in database. My big problem is the "INSERT INTO" statement, after searching and debugging still no success. This is a part of the code:
Private Sub btnAdd_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnAdd.Click
Dim sqlinsert As String = "INSERT INTO tblList([Access Number],[Book Title],Subject,Author,Edition,Page,Publisher,Years,Copy)" & "VALUES(#Access Number,#Book Title,#Subject,#Author,#Edition,#Page,#Publisher,#Years,#Copy)"
Dim cmd As New OleDbCommand(sqlinsert, con)
cmd.Parameters.Add(New OleDbParameter("#Access Number", txtan.Text))
cmd.Parameters.Add(New OleDbParameter("#Book Title", txtbt.Text))
cmd.Parameters.Add(New OleDbParameter("#Subject", txtsub.Text))
cmd.Parameters.Add(New OleDbParameter("#Author", txtau.Text))
cmd.Parameters.Add(New OleDbParameter("#Edition", txted.Text))
cmd.Parameters.Add(New OleDbParameter("#Page", txtpg.Text))
cmd.Parameters.Add(New OleDbParameter("#Publisher", txtpub.Text))
cmd.Parameters.Add(New OleDbParameter("#Years", txtyr.Text))
cmd.Parameters.Add(New OleDbParameter("#Copy", txtco.Text))
cmd.ExecuteNonQuery()
MsgBox("One Record Added")
Refreshlist()
clear()
End Sub
Help me please? I am so confused.
Thanks a lot.
(A am using ms access and vb.net in visual studio 2008)

Upon digging on some of my old programs, this is how I pass parameters to ms access:
Dim sqlinsert As String= "INSERT INTO tblList([Access Number],[Book Title],Subject,Author,Edition,Page,Publisher,Years,Copy)" & _
"VALUES(?,?,?,?,?,?,?,?,?)"
Dim cmd as new OleDbCommand(sqlinsert, con)
cmd.Connection.Open
With cmd.Parameters
.AddWithValue("access_number", txtan.text)
.AddWithValue("book_title", txtbt.text)
.AddWithValue("subject", txtsub.text)
.AddWithValue("author", txtau.text)
.AddWithValue("edition", txted.text)
.AddWithValue("page", txtpg.text)
.AddWithValue("publisher", txtpub.text)
.AddWithValue("years", txtyr.text)
.AddWithValue("copy", txtco.text)
End With
cmd.ExecuteNonQuery()
Also, I'd be wary of using spaces on your column names,
specifically on Access Number and Book Title
P.S.
.AddWithValue("a", b)
a = this can be anything but as a personal rule of mine, i tend to name it based on the column name
b = the value you want to pass

Try change the name of these parameters from
"#Access Number" to: "#Access_Number"
"#Book Title" to: "#Book_Title"

Related

HOW to fix overflow exception while connecting to ms access database from visual basic 2010

I am new to visual basic. I am developing a project in visual basic 2010 for my mini project.I wanted to store my data inserted in visual basic form into the database created in ms access 2007.I have typed the following code but, each time i enter the values into the form and press submit I get the exception as "overflow" in a message box . I couldn't able to find out the reason for this. Please help me out.
THE FOLLOWING IS THE CODE:
Imports System.Data.OleDb
Public Class dn_register
Dim provider As String
Dim dataFile As String
Dim connString As String
Dim myConnection As OleDbConnection = New OleDbConnection
Private Sub dn_sub_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles dn_sub.Click
provider = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source="
dataFile = "F:\MyDatabase\MyProjectDatabase.accdb"
connString = provider & dataFile
myConnection.Close()
myConnection.ConnectionString = connString
myConnection.Open()
Dim str As String
str = "Insert into Dnr_tbl([Dname],[Age],[Bloodgroup],[Location],[Contact],[Email]) Values(?,?,?,?,?,?)"
Dim cmd As OleDbCommand = New OleDbCommand(str, myConnection)
cmd.Parameters.Add(New OleDbParameter("Dname", CType(TextBox1.Text, String)))
cmd.Parameters.Add(New OleDbParameter("Age", CType(TextBox2.Text, Integer)))
cmd.Parameters.Add(New OleDbParameter("Bloodgroup", CType(TextBox3.Text, String)))
cmd.Parameters.Add(New OleDbParameter("Location", CType(TextBox4.Text, String)))
cmd.Parameters.Add(New OleDbParameter("Contact", CType(TextBox5.Text, String)))
cmd.Parameters.Add(New OleDbParameter("Email", CType(TextBox6.Text, String)))
Try
cmd.ExecuteNonQuery()
cmd.Dispose()
myConnection.Close()
TextBox1.Clear()
TextBox2.Clear()
TextBox3.Clear()
TextBox4.Clear()
TextBox5.Clear()
TextBox6.Clear()
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
End Class
And here is the snapshot of my error message
My guess is that this line is throwing the exception:
cmd.Parameters.Add(New OleDbParameter("Age", CType(TextBox2.Text, Integer)))
My first suggestion is to use the appropriate control to handle numeric input such as a NumericUpDown control.
My second suggestion (if you continue to use a TextBox) is to explicitly convert the String value to an Integer using Integer.TryParse.
My third suggestion is to stop using CType on String values (textBox[n].Text) to convert them to Strings, it is unnecessary.
My fourth suggestion is to use Parameter.AddWithValue instead since it will use the data type of the value passed.
My fifth and final suggestion is to wrap your objects that implement iDisposable in Using statements or to at least explicitly dispose of them.
Here is an example of implementing suggestions 2-5, if you take my first suggestion, then #2 is unnecessary:
'Declare an age variable that is an Integer
Dim age As Integer
'Convert the String to an Integer
If Integer.TryParse(TextBox2.Text, age) Then
'Declare the connection object
Dim con As OleDbConnection
'Database operations should always be wrapped in Try/Catch
Try
'Set the connection object to a new instance
con = New OleDbConnection(connString)
'Create a new instance of the command object
Using cmd As OleDbCommand = New OleDbCommand("INSERT INTO [Dnr_tbl] ([Dname], [Age], [Bloodgroup], [Location], [Contact], [Email]) VALUES (#name, #age, #bloodgroup, #location, #contact, #email)", con)
'Parameterize the query
With cmd.Parameters
.AddWithValue("#name", TextBox1.Text)
.AddWithValue("#age", age)
.AddWithValue("#bloodgroup", TextBox3.Text)
.AddWithValue("#location", TextBox4.Text)
.AddWithValue("#contact", TextBox5.Text)
.AddWithValue("#email", TextBox6.Text)
End With
'Open the connection
con.Open()
'Execute the query
cmd.ExecuteNonQuery()
'Close the connection
con.Close()
'Clear the controls
TextBox1.Clear() : TextBox2.Clear() : TextBox3.Clear() : TextBox4.Clear() : TextBox5.Clear() : TextBox6.Clear()
End Using
Catch ex As Exception
MessageBox.Show(ex.ToString())
Finally
'Check if the connection object was initialized
If con IsNot Nothing Then
If con.State = ConnectionState.Open Then
'Close the connection if it was left open(exception thrown)
con.Close()
End If
'Dispose of the connection object
con.Dispose()
End If
End Try
Else
MessageBox.Show("Invalid age input.")
End If
First try to narrow down which parameter is causing the problem. You can either comment out all of the parameters and add them back until you find the problem (adjusting the SQL statement as needed to match the parameter count) or pick a likely suspect and comment it out and continue commenting out parameters and adjusting the SQL statement until it works. You may need to temporarily tweak the table in Access to allow nulls in the tested columns. The integer value does seem a likely candidate and I would start from there.
Once you find the problem parameter, it may be obvious that there's a datatype conflict or mismatch between VB.NET and Access or you may have to experiment a little to find which VB cast will work. The next most likely candidate in your example would be a string length problem and that would be pretty obvious from looking at the table definition and your text box input length limits.

How do you stop and reset a form before it submits data to a database

I am making a login page and I have done the registration form, however, I need to validate the username. I have done the validating part, however, I can't seem to get it to not submit the data and reset the username box. This is the code
Imports System.Data.OleDb
Public Class Register
Dim provider As String
Dim dataFile As String
Dim connString As String
Dim myConnection As OleDbConnection = New OleDbConnection
Private Sub rB_Click(sender As Object, e As EventArgs) Handles rB.Click
provider = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source ="
dataFile = "C:\Users\Harry\Documents\Visual Studio 2015/users.accdb"
connString = provider & dataFile
myConnection.ConnectionString = connString
myConnection.Open()
Dim usf As OleDbCommand = New OleDbCommand("SELECT * FROM [users] WHERE [username] = '" & uT.Text, myConnection)
Dim userFound As Boolean = True
If userFound = True Then
MsgBox("Username already found; Please choose another")
Dim frm = New Register
frm.Show()
Me.Close()
End If
Dim str As String
str = "insert into users ([username], [password], [Firstname], [LastName]) values (?, ?, ?, ?)"
Dim cmd As OleDbCommand = New OleDbCommand(str, myConnection)
cmd.Parameters.Add(New OleDbParameter("username", CType(uT.Text, String)))
cmd.Parameters.Add(New OleDbParameter("password", CType(pT.Text, String)))
cmd.Parameters.Add(New OleDbParameter("FirstName", CType(fnT.Text, String)))
cmd.Parameters.Add(New OleDbParameter("LastName", CType(lnT.Text, String)))
Try
cmd.ExecuteNonQuery()
cmd.Dispose()
myConnection.Close()
uT.Clear()
pT.Clear()
fnT.Clear()
lnT.Clear()
Me.Hide()
Form2.Show()
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
First, please post your code instead of including an image as it's hard to reference back to when describing problems found.
That being said. You have a boolean UserFound that you are declaring and setting to True and then immediately checking to see if it's true. Of course it's going to be true, you just set it.
Also, I see nowhere in that image where you're even passing the query to get results back. (ie, executeReader, executeScalar)
Typically you can query the database and then check to see if any rows were returned or use executeScalar against a single column to see if a value was returned.

No value given for one or more required parameters vb.net oledb

Public Class ViewPhoneRecords
Dim con As New OleDb.OleDbConnection
Dim dbProvider As String
Dim dbSource As String
Dim da As OleDb.OleDbDataAdapter
Dim ds As New DataSet
Dim sqlquery As New OleDb.OleDbCommand
Dim con1 As New OleDbConnection("PROVIDER=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Database.accdb")
Private Sub SaveBtn_Click(sender As Object, e As EventArgs) Handles SaveBtn.Click
Dim sqlupdate As String
' Here we use the UPDATE Statement to update the information. To be sure we are
' updating the right record we also use the WHERE clause to be sureno information
' is added or changed in the other records
sqlupdate = "UPDATE PhoneRecords SET Forename=#Forename, Surname=#Surname, Address=#Address, PhoneModel=#PhoneModel, PhoneNumber=#PhoneNumber, Postcode=#Postcode WHERE IDNum='" & IDTextBox.Text & "'"
Dim cmd As New OleDbCommand(sqlupdate, con1)
' This assigns the values for our columns in the DataBase.
' To ensure the correct values are written to the correct column
cmd.Parameters.Add(New OleDbParameter("#Forename", ForenameTextBox1.Text))
cmd.Parameters.Add(New OleDbParameter("#Surname", SurnameTextBox1.Text))
cmd.Parameters.Add(New OleDbParameter("#Address", AddressTextBox1.Text))
cmd.Parameters.Add(New OleDbParameter("#PhoneModel", PhoneModelTextBox1.Text))
cmd.Parameters.Add(New OleDbParameter("#PhoneNumber", PhoneNumberTextBox1.Text))
cmd.Parameters.Add(New OleDbParameter("#Postcode", PostcodeTextBox1.Text))
con1.Open()
cmd.ExecuteNonQuery()
MsgBox("Row(s) Inserted !! ") 'Displays message box informing the user that the database has been added to
con1.Close() 'Connection closed
Me.Refresh()
End Sub
This is supposed to update a selected record in a datagrid view. However, when I click the 'Save changes' button, an error is given; "No value given for one or more parameters." Any idea how to solve this?
Use cmd.Parameters.AddWithValue instead of cmd.Parameters.Add

Duplicate Random numbers in Visual Studio 2010

I am new to Vb . I am trying to make a project on railway reservation system . I want to generate random ticket number and save it to the ms.access 2007 file . So far , everything is quite working properly but the problem I am having is that when I run the program and book two tickets one after another (without stop debugging ) , it generates two different random ticket numbers and saves them to the ms.access file but when I book one ticket and then stop debugging and after that debug again and book another ticket , it generates the same ticket number as it generated for the first ticket which I booked when I debug for the first time . Could you help me how should I fix this issue ? Thank you !
This is my code
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim value As Integer = CInt(Int((47563 * Rnd()) + 1))
Dim str As String
str = "insert into Table2 ([P_Name], [Age], [Phone], [Train_Name], [Seat_No],[Berth],[Tnumber]) values (?, ?, ?, ?, ?,?,?)"
Dim cmd As OleDbCommand = New OleDbCommand(str, Conn)
cmd.Parameters.Add(New OleDbParameter("P_Name", CType(TextBox1.Text, String)))
cmd.Parameters.Add(New OleDbParameter("Age", CType(TextBox2.Text, Integer)))
cmd.Parameters.Add(New OleDbParameter("Phone", CType(TextBox3.Text, String)))
cmd.Parameters.Add(New OleDbParameter("Train_Name", CType(TextBox4.Text, String)))
cmd.Parameters.Add(New OleDbParameter("Seat_No", CType(TextBox5.Text, Integer)))
cmd.Parameters.Add(New OleDbParameter("Berth", CType(TextBox6.Text, String)))
cmd.Parameters.Add(New OleDbParameter("Tnumber", CType(value, Integer)))
Try
cmd.ExecuteNonQuery()
cmd.Dispose()
Conn.Close()
TextBox1.Clear()
TextBox2.Clear()
TextBox3.Clear()
TextBox4.Clear()
TextBox5.Clear()
TextBox6.Clear()
MsgBox("Ticket Booked Successfully !!! ")
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
Instead of the Rnd() function, instantiate a Random object and use that.
Dim random As Random = New Random
Dim ticketNumber As Int32 = random.Next(1, 47563)
Note though that this is an absolute TERRIBLE way to generate a ticket number. You will ALWAYS get ticket number collisions if you use random numbers.
Alternative methods would be to use the system date/time (to the millisecond) to generate unique ticket numbers.
Or use a Guid.
Or an AutoNumber (IDENTITY) column in your database.
Or any other method that gives you a non-repeating sequence of numbers / characters.
You can use GUID or Date format for Unuqie Number.
For example:
Now : 2015/03/14 13:10:52 your unique number may be 20150314131052.

Creating new records in MSACCESS Table

I am attempting to create a new record from vb.net to an msaccess table, which i am able to do, but i have to add in the next consecutive ID number for it to actually save. For instance, if the next ID in the Access DB is 4, i have to type in 4 in the id textfield on my form. Code below:
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
Dim sqlinsert As String
' We use the INSERT statement which tells our program to add the information
' from the Forms Text fields into the Databases columns.
sqlinsert = "INSERT INTO Table1(Title, YearofFilm, Description, Field1, ID)" & _
"VALUES(#Title, #YearofFilm, #Description, #Field1, #ID)"
Dim cmd As New OleDbCommand(sqlinsert, con1)
' This assigns the values for our columns in the DataBase.
' To ensure the correct values are written to the correct column
cmd.Parameters.Add(New OleDbParameter("#Title", TextBox1.Text))
cmd.Parameters.Add(New OleDbParameter("#YearofFilm", Convert.ToInt32(TextBox2.Text)))
cmd.Parameters.Add(New OleDbParameter("#Description", TextBox3.Text))
cmd.Parameters.Add(New OleDbParameter("#Field1", TextBox4.Text))
cmd.Parameters.Add(New OleDbParameter("#ID", Convert.ToInt32(TextBox5.Text)))
' This is what actually writes our changes to the DataBase.
' You have to open the connection, execute the commands and
' then close connection.
con1.Open()
cmd.ExecuteNonQuery()
con1.Close()
' This are subs in Module1, to clear all the TextBoxes on the form
' and refresh the DataGridView on the MainForm to show our new records.
ClearTextBox(Me)
RefreshDGV()
Me.Close()
End Sub
How can i tell textbox5 which is the ID field, to be the next number in the access db?
Open your Access database, show the structure of your table and change the ID field type from numeric to AutoNumber.
Now your code don't need to pass anything to Access because the number will be handled automatically from Access.
You could just add these lines to your code to get back the number assigned by Access to your field
Dim sqlinsert As String
sqlinsert = "INSERT INTO Table1(Title, YearofFilm, Description, Field1)" & _
"VALUES(#Title, #YearofFilm, #Description, #Field1)"
Dim cmd As New OleDbCommand(sqlinsert, con1)
cmd.Parameters.Add(New OleDbParameter("#Title", TextBox1.Text))
cmd.Parameters.Add(New OleDbParameter("#YearofFilm", Convert.ToInt32(TextBox2.Text)))
cmd.Parameters.Add(New OleDbParameter("#Description", TextBox3.Text))
cmd.Parameters.Add(New OleDbParameter("#Field1", TextBox4.Text))
con1.Open()
cmd.ExecuteNonQuery()
cmd.Parameters.Clear()
cmd.CommandText = "SELECT ##IDENTITY"
Dim assignedID = Convert.ToInt32(cmd.ExecuteScalar())
' Eventually
TextBox5.Text = assignedID.ToString
con1.Close()
......
See also
How to retrieve last autoincremented value in MS-Access like ##Identity in Sql Server
Create a SELECT statement to retrieve the Max number form the table and add one to it. I do not know VB.Net, so it should be something like.
maxQry = "SELECT Max(IDColumnName) As MaxID FROM theTableName;"
Dim cmd As New OleDbCommand(maxQry, con1)
dr = cmd.ExecuteReader
If dr.HasRows Then
While dr.Read()
TextBox5.Text = dr("MaxID").ToString
End While
End If
Unless the field is an AutoNumber type you do not have to worry about it at all.