Adding data to Access Database through Visual Basic Form - database

I have a forum where I want the user to type a profile name and then click Add and then it will add what they typed in the text box the the ProfileName field in my table. When I click the Add button, it comes up with an error that says An unhandled exception of type System.Data.OleDb.OleDbException occurred in system.data.dll. Here is my code:
Private Sub RefreshData()
Dim cnn As New OleDb.OleDbConnection
If Not cnn.State = ConnectionState.Open Then
cnn.Open()
End If
Dim da As New OleDb.OleDbDataAdapter("SELECT id AS [ID], " & _
"ProfileName AS [Name] " & _
" FROM Profile ORDER BY id", cnn)
Dim dt As New DataTable
da.Fill(dt)
cnn.Close()
Me.dgvData.DataSource = dt
End Sub
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
If (TextBox1.Text = "") Then
MsgBox("Please enter a profile name.")
Else
Dim cnn As New OleDb.OleDbConnection("Provider=Microsof… Source=c:\Data\Database.mdb ;Extended Properties=Paradox 5.x;")
Dim cmd As New OleDb.OleDbCommand
If Not cnn.State = ConnectionState.Open Then
cnn.Open()
End If
cmd.Connection = cnn
cmd.CommandText = "INSERT INTO Profile(ProfileName) " & _
"VALUES (" & Me.TextBox1.Text & "')"
cmd.ExecuteNonQuery()
cnn.Close()
Dim oForm As addsnake
oForm = New addsnake
oForm.Show()
oForm = Nothing
Me.Close()
End If
End Sub

Without further information I suggest that:
You don't need to give id an alias of ID:
SELECT id AS [ID]
you might still enclose it in square-brackets though, if you like:
SELECT [id]
You are missing an apostrophe in the following line:
"VALUES (" & Me.TextBox1.Text & "')"
Also check your connection string at connectionstrings.com

Related

I want to update my data of my database in VB.net but I get Error Syntax

This is my problem:
When I click update button, I don't know how to fix this error:
My Error Message is:
"Error: syntax error in union query"
This is my code:
Private Sub btnUpdate_Click(sender As Object, e As EventArgs) Handles btnUpdate.Click
TestConnection()
Try
Dim cmd As OleDbCommand
Dim sql As String
sql = "(UPDATE tblUsers SET Username = '" & txtUserName.Text & "', Password = '" & txtUserPassword.Text &
"', Usertype = '" & cbousertype.Text & "', WHERE UserID = '" & txtUserID.Text & "');"
cmd = New OleDbCommand(sql, Conn)
cmd.ExecuteNonQuery()
Catch ex As Exception
MsgBox("Error: " & ex.Message)
End Try
End Sub
Is it wrong?
Now my problem has been solved thank you very much
i changed my code to use a parameters and then it work
Now my code is :
Private Sub btnUpdate_Click(sender As Object, e As EventArgs) Handles btnUpdate.Click
TestConnection()
Dim cmd As OleDbCommand
Dim sql As String
sql = "UPDATE tblUsers SET Username=?, [Password]=?, Usertype=? where UserID=?"
cmd = New OleDbCommand(sql, Conn)
cmd.Parameters.AddWithValue("#p1", txtUserName.Text)
cmd.Parameters.AddWithValue("#p2", txtUserPassword.Text)
cmd.Parameters.AddWithValue("#p3", cbousertype.Text)
cmd.Parameters.AddWithValue("#p4", txtUserID.Text)
cmd.ExecuteNonQuery()
MsgBox("Data Has Been Updated", MsgBoxStyle.Information, "Updated")
ShowUser()
End Sub

Unable to convert System.Date and System.int to System.String, error

I'm trying to search a keyword in the SQL Server db from Textbox1 and printing the corresponding details in other TextBoxes.
While running the below code, it shows it is unable to convert the DateTime and Integer value into String to display it in the TextBoxes.
Also there is another end of statement expected error in the command.Parameter line:
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim connection As New SqlConnection("Server= DESKTOP-STMQUHM; Database = HospitalDB;Trusted_Connection=True")
Dim command As New SqlCommand("select * from Medicines where MedicineName ='" & TextBox1.Text & "' ", connection)
command.Parameters.Add("#Textbox1",SqlDbType.Text)Value=TextBox1.Text 'Another error
Dim adapter As New SqlDataAdapter(command)
Dim table As New DataTable()
adapter.Fill(table)
TextBox1.Text = ""
TextBox2.Text = ""
TextBox3.Text = ""
TextBox4.Text = ""
If table.Rows.Count() > 0 Then
TextBox1.Text = table.Rows(0)(1).ToString
TextBox2.Text = table.Rows(0)(2).ToString
TextBox3.Text = table.Rows(0)(3).ToString
TextBox4.Text = table.Rows(0)(4).ToString
Else
MessageBox.Show("NO DATA FOUND!!")
End If
End Sub
Try to change this:
Dim command As New SqlCommand("select * from Medicines where MedicineName ='" & TextBox1.Text & "' ", connection)
command.Parameters.Add("#Textbox1",SqlDbType.Text)Value=TextBox1.Text
Into this:
Dim command As New SqlCommand("select * from Medicines where MedicineName = #MedicineName", connection)
command.Parameters.Add("#MedicineName",SqlDbType.Text).Value=TextBox1.Text
This is because you have not declared the parameter name into your original SQL string, then on the second line of your code, before Value, you're missing a dot.

Getting Dropdownlist selected value in vb.net

I am trying to set user account for my system. I have two tables (User and Staff)
And this is the interface for setting up user
the name dropdownlist need to be bound to staff table where I can display a list of staff members. When I insert these data to the user table I need to convert the selected staff name into its ID.
I'm really weak in programming and if possible help me with this.
this is the code I am using
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles btnUserAdd.Click
If ValidData() Then
Try
cmd.Connection = con
con.Open()
sel_id = Convert.ToString(cmbStaffName.SelectedValue)
cmd.CommandType = System.Data.CommandType.Text
cmd.CommandText = "Insert Into dbo.[User] (User_ID,Employee_ID,User_Name,Password,User_Level) values ('" & txtBoxUserID.Text & "','" & sel_id & "','" & txtBoxUserName.Text & "', '" & txtBoxPassword.Text & "','" & ComboBox1.Text & "')"
cmd.ExecuteNonQuery()
MsgBox("Succesfully Added", MsgBoxStyle.Information, "add")
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
con.Close()
End If
If Not ValidData() Then
Exit Sub
End If
End Sub
Private Sub btnUserUpdate_Click(sender As Object, e As EventArgs) Handles btnUserUpdate.Click
End Sub
Private Sub Setup_User_Load(sender As Object, e As EventArgs) Handles MyBase.Load
'TODO: This line of code loads data into the 'MyHotelManagementSystemDataSet19.Staff' table. You can move, or remove it, as needed.
Me.StaffTableAdapter1.Fill(Me.MyHotelManagementSystemDataSet19.Staff)
'TODO: This line of code loads data into the 'MyHotelManagementSystemDataSet18.Staff' table. You can move, or remove it, as needed.
Me.User_TypeTableAdapter.Fill(Me.MyHotelManagementSystemDataSet17.User_Type)
End Sub
Private Sub cmbStaffName_SelectedIndexChanged(sender As Object, e As EventArgs) Handles cmbStaffName.SelectedIndexChanged
Try
con.Open()
ds = New DataSet()
cmd = New SqlCommand("select * from Staff", con)
Adapter = New SqlDataAdapter(cmd)
adapter.Fill(ds)
cmbStaffName.DataSource = StaffBindingSource1
cmbStaffName.DisplayMember = "Name"
cmbStaffName.ValueMember = "Employee_ID"
Catch ex As Exception
Finally
con.Close()
End Try
End Sub
Private Sub cmbStaffName_SelectedIndexChanged(sender As Object, e As EventArgs) Handles cmbStaffName.SelectedIndexChanged
Try
con.Open()
ds = New DataSet()
cmd = New SqlCommand("select * from Staff", con)
Using adapter as New SqlDataAdapter(cmd)
adapter.Fill(ds)
End Using
cmbStaffName.DisplayMember = "Name"
cmbStaffName.ValueMember = "Employee_ID"
cmbStaffName.DataSource = ds
Catch ex As Exception
Finally
con.Close()
End Try
End Sub

Getting an exception while accessing an Access database

I need to insert a row into the Access table. I have been getting
object reference not set to instance of an object
My code is:
Private Sub Button2_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button2.Click
Dim strconstring As String = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Documents and Settings\Daisy\My Documents\Downloads\MusicSales.mdb"
Dim objcon As OleDb.OleDbConnection
objcon = New OleDb.OleDbConnection(strconstring)
Dim objcommand As OleDb.OleDbCommand
Dim da As New OleDb.OleDbDataAdapter
Try
objcon.Open()
Dim command As String
command = "insert into Artists(Artist, Company, Sales )" _
& " values('" & ArtistBox.Text & "', '" _
& TextBox2.Text & "', " & TextBox3.Text & ")"
objcommand = New OleDb.OleDbCommand(command, objcon)
da.InsertCommand.CommandText = command
da.InsertCommand.ExecuteNonQuery()
Catch exceptionobject As Exception
MessageBox.Show(exceptionobject.Message)
Finally
objcon.Close()
End Try
End Sub
Your connection string is a bit of a mess, so that may be causing the problem. Use EITHER...
Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Documents and Settings\Daisy\My Documents\Downloads\MusicSales.mdb;
...OR...
Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Documents and Settings\Daisy\My Documents\Downloads\MusicSales.mdb;

Exception causing VB.NET code to not run properly

I am getting an exception when I run the below VB.NET code to validate a user..The exception says that "Incorrect syntax near variable user"
Can anyone tell me where am I going wrong ?
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
If TextBox1.Text.Trim().Length = 0 Or TextBox2.Text.Trim().Length = 0 Then
MsgBox("Enter a user id and password")
Return 'Terminate this method
End If
Dim myconnection As SqlConnection
Dim mycommand As SqlCommand
Dim dr As SqlDataReader
Dim userid = TextBox1.Text
Dim password = TextBox2.Text
Try
myconnection = New SqlConnection("server=PARTH- PC\SQLEXPRESS;uid=sa;pwd=parth;database=fcrit")
myconnection.Open()
mycommand = New SqlCommand("select * from user where [user id]=#userid and [password]=#password", myconnection)
mycommand.Parameters.Add("#userid", SqlDbType.VarChar, 30).Value = userid
mycommand.Parameters.Add("#password", SqlDbType.VarChar, 30).Value = password
'mycommand = New SqlCommand("select * from user where user id='" & TextBox1.Text & "' and password='" & TextBox2.Text & "'", myconnection)
dr = mycommand.ExecuteReader()
If (dr IsNot Nothing) Then
If (dr.Read()) Then
MsgBox("User is authenticated")
Form2.Show()
Else
MsgBox("Please enter correct username and password")
End If
End If
myconnection.Close()
Catch ex As Exception
Throw
Finally
End Try
End Sub
Try changing your SQL to -
"select * from [user] where [user id]=#userid and [password]=#password"
According to this page 'User' is a reserved word
User is a reserved word in SQL Server.
Put brackets around the table name:
mycommand = New SqlCommand("select * from [user] where [user id]=#userid and [password]=#password", myconnection)

Resources