Related
Hi i'm making an accounting software for small business as a freelance where I have to store invoice also make ledger from it's query I had created another table for ledger and one table for invoice items but now problem is when I insert in ledger first all the details of ledger is insert into invoice too if I move to invoice before ledger it gives error of parameter has no default value. my code looks like this
Private Sub add_Click(sender As Object, e As EventArgs) Handles add.Click
If client_name.Text = "" Or company_name.Text = "" Or email.Text = "" Or contact_no.Text = "" Or address.Text = "" Or delivery_address.Text = "" Then
MessageBox.Show("Please Fill all fields", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
Else
If issaved = 1 Then
MessageBox.Show("Fees already saved", "Fees saved", MessageBoxButtons.OK, MessageBoxIcon.Error)
Else
saveorder()
issaved = 1
End If
End If
End Sub
Public Sub saveorder()
cn.Close()
cn.Open()
Dim debit As Int64 = Convert.ToInt64(total_basic_amount.Text) + Convert.ToInt64(freigh_rate.Text) + Convert.ToInt64(delivery_rate.Text)
cmd.Connection = cn
cmd.CommandText = "insert into ledger([client_name],[registration_no],[company_name],[date],[credit],[debit])Values(#client_name,#registration_no,#company_name,#date,#credit,#debit)"
cmd.Parameters.Add(New OleDbParameter("#client_name", client_name.Text.ToString))
cmd.Parameters.AddWithValue("#registration_no", reg_no.Text.ToString)
cmd.Parameters.AddWithValue("#company_name", company_name.Text.ToString)
cmd.Parameters.AddWithValue("#date", datetime.Value.ToShortDateString)
cmd.Parameters.AddWithValue("#credit", 0)
cmd.Parameters.Add(New OleDbParameter("#debit", debit))
cmd.ExecuteNonQuery()
MessageBox.Show("ledger debit stored")
cn.Close()
cn.Open()
cmd.Connection = cn
cmd.CommandText = "insert into ledger([client_name],[registration_no],[company_name],[date],[credit],[debit])Values(#client_name,#registration_no,#company_name,#date,#credit,#debit)"
cmd.Parameters.AddWithValue("#client_name", client_name.Text.ToString)
cmd.Parameters.AddWithValue("#registration_no", reg_no.Text.ToString)
cmd.Parameters.AddWithValue("#company_name", company_name.Text.ToString)
cmd.Parameters.AddWithValue("#date", datetime.Value.ToShortDateString)
cmd.Parameters.AddWithValue("#credit", Convert.ToInt64(advance_received_amount.Text.ToString))
cmd.Parameters.AddWithValue("#debit", 0)
cmd.ExecuteNonQuery()
MessageBox.Show("ledger credit stored")
cn.Close()
cn.Open()
cmd.Connection = cn
cmd.CommandText = "insert into invoice([invoice_date],[client_name],[client_company_name],[client_email],[client_contact_no],[client_address],[client_delivery_address],[total_basic_amount],[freight_rate],[delivery_rate],[advanced_amount],[pending_amount])
values(#invoice_date,#client_name,#client_company_name,#client_email,#client_contact_no,#client_address,#client_delivery_address,#total_basic_amount,#freight_rate,#delivery_rate,#advanced_amount,#pending_amount)"
cmd.Parameters.AddWithValue("#invoice_date", datetime.Value.ToShortDateString)
cmd.Parameters.AddWithValue("#client_name", client_name.Text.ToString)
cmd.Parameters.AddWithValue("#client_company_name", company_name.Text.ToString)
cmd.Parameters.AddWithValue("#client_email", email.Text.ToString)
cmd.Parameters.AddWithValue("#client_contact_no", contact_no.Text.ToString)
cmd.Parameters.AddWithValue("#client_address", address.Text.ToString)
cmd.Parameters.AddWithValue("#client_delivery_address", delivery_address.Text.ToString)
cmd.Parameters.AddWithValue("#total_basic_amount", total_basic_amount.Text.ToString)
cmd.Parameters.AddWithValue("#freight_rate", freigh_rate.Text.ToString)
cmd.Parameters.AddWithValue("#delivery_rate", delivery_rate.Text.ToString)
cmd.Parameters.AddWithValue("#advanced_amount", advance_received_amount.Text.ToString)
cmd.Parameters.AddWithValue("#pending_amount", total_pending_amount.Text.ToString)
cmd.ExecuteNonQuery()
MessageBox.Show("invoice stored")
cn.Close()
cn.Open()
For i As Integer = 0 To DataGridView1.Rows.Count - 1
cmd.Connection = cn
cmd.CommandText = "insert into invoice_items([invoice_id],[item_name],[qty],[rate])Values(#invoice_id,#item_name,#qty,#rate)"
cmd.Parameters.AddWithValue("#invoice_id", invoice_id.Text.ToString)
cmd.Parameters.AddWithValue("#item_name", DataGridView1.Rows(i).Cells(2).Value)
cmd.Parameters.AddWithValue("#qty", DataGridView1.Rows(i).Cells(3).Value)
cmd.Parameters.AddWithValue("#rate", DataGridView1.Rows(i).Cells(4).Value)
cmd.ExecuteNonQuery()
Next
End Sub
Public Sub saveorder()
cn.Close()
cn.Open()
Dim debit As Int64 = Convert.ToInt64(total_basic_amount.Text) + Convert.ToInt64(freigh_rate.Text) + Convert.ToInt64(delivery_rate.Text)
cmd.Connection = cn
cmd.CommandText = "insert into ledger([client_name],[registration_no],[company_name],[date],[credit],[debit])Values(#client_name,#registration_no,#company_name,#date,#credit,#debit)"
cmd.Parameters.Add(New OleDbParameter("#client_name", client_name.Text.ToString))
cmd.Parameters.AddWithValue("#registration_no", reg_no.Text.ToString)
cmd.Parameters.AddWithValue("#company_name", company_name.Text.ToString)
cmd.Parameters.AddWithValue("#date", datetime.Value.ToShortDateString)
cmd.Parameters.AddWithValue("#credit", 0)
cmd.Parameters.Add(New OleDbParameter("#debit", debit))
cmd.ExecuteNonQuery()
MessageBox.Show("ledger debit stored")
cn.Close()
cn.Open()
cmd.Connection = cn
cmd.CommandText = "insert into ledger([client_name],[registration_no],[company_name],[date],[credit],[debit])Values(#client_name,#registration_no,#company_name,#date,#credit,#debit)"
cmd.Parameters.AddWithValue("#client_name", client_name.Text.ToString)
cmd.Parameters.AddWithValue("#registration_no", reg_no.Text.ToString)
cmd.Parameters.AddWithValue("#company_name", company_name.Text.ToString)
cmd.Parameters.AddWithValue("#date", datetime.Value.ToShortDateString)
cmd.Parameters.AddWithValue("#credit", Convert.ToInt64(advance_received_amount.Text.ToString))
cmd.Parameters.AddWithValue("#debit", 0)
cmd.ExecuteNonQuery()
MessageBox.Show("ledger credit stored")
cn.Close()
cn.Open()
cmd.Connection = cn
cmd.CommandText = "insert into invoice([invoice_date],[client_name],[client_company_name],[client_email],[client_contact_no],[client_address],[client_delivery_address],[total_basic_amount],[freight_rate],[delivery_rate],[advanced_amount],[pending_amount])
values(#invoice_date,#client_name,#client_company_name,#client_email,#client_contact_no,#client_address,#client_delivery_address,#total_basic_amount,#freight_rate,#delivery_rate,#advanced_amount,#pending_amount)"
cmd.Parameters.AddWithValue("#invoice_date", datetime.Value.ToShortDateString)
cmd.Parameters.AddWithValue("#client_name", client_name.Text.ToString)
cmd.Parameters.AddWithValue("#client_company_name", company_name.Text.ToString)
cmd.Parameters.AddWithValue("#client_email", email.Text.ToString)
cmd.Parameters.AddWithValue("#client_contact_no", contact_no.Text.ToString)
cmd.Parameters.AddWithValue("#client_address", address.Text.ToString)
cmd.Parameters.AddWithValue("#client_delivery_address", delivery_address.Text.ToString)
cmd.Parameters.AddWithValue("#total_basic_amount", total_basic_amount.Text.ToString)
cmd.Parameters.AddWithValue("#freight_rate", freigh_rate.Text.ToString)
cmd.Parameters.AddWithValue("#delivery_rate", delivery_rate.Text.ToString)
cmd.Parameters.AddWithValue("#advanced_amount", advance_received_amount.Text.ToString)
cmd.Parameters.AddWithValue("#pending_amount", total_pending_amount.Text.ToString)
cmd.ExecuteNonQuery()
MessageBox.Show("invoice stored")
cn.Close()
cn.Open()
For i As Integer = 0 To DataGridView1.Rows.Count - 1
cmd.Connection = cn
cmd.CommandText = "insert into invoice_items([invoice_id],[item_name],[qty],[rate])Values(#invoice_id,#item_name,#qty,#rate)"
cmd.Parameters.AddWithValue("#invoice_id", invoice_id.Text.ToString)
cmd.Parameters.AddWithValue("#item_name", DataGridView1.Rows(i).Cells(2).Value)
cmd.Parameters.AddWithValue("#qty", DataGridView1.Rows(i).Cells(3).Value)
cmd.Parameters.AddWithValue("#rate", DataGridView1.Rows(i).Cells(4).Value)
cmd.ExecuteNonQuery()
Next
End Sub
I also tried connection open close before after to reset but it didn't work
Always clear parameters before starting a new run using the same command:
cmd.Parameters.Clear();
The question:
-Display a message for validation if the user entered existing data (name, staff id, phone number, username and password).
THESE ARE THE CODES
my database works but the msgbox appeared saying the command text wat not set for the command object
pro = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=D:\SEM 5\CSC301\ASSESSMENT 3\database.accdb"
connstring = pro
myconnection.ConnectionString = connstring
myconnection.Open()
Dim con As New OleDbConnection
con.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=D:\SEM 5\CSC301\ASSESSMENT 3\database.accdb"
con.Open()
Dim registercmd As OleDbCommand = New OleDbCommand("select * from users where [Librarian Name]='" & txtName.Text & "' or [Staff ID]='" &
txtStaffID.Text & "' or [Phone Number]='" & txtPhone.Text & "' or [Username]='" &
txtUsername.Text & "' or [Password]='" & txtPassword.Text & "'", con)
Dim registerrd As OleDbDataReader = registercmd.ExecuteReader
If (registerrd.Read() = True) Then
Me.Hide()
MessageBox.Show("Account Exist!", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
Me.Hide()
Me.Show()
txtName.Clear()
txtStaffID.Clear()
txtPhone.Clear()
txtUsername.Clear()
txtPassword.Clear()
Else
command = "insert into users([Librarian Name],[Staff ID],[Phone Number],[Username],[Password])
Values('" & txtName.Text & "','" & txtStaffID.Text & "','" & txtPhone.Text & "','" & txtUsername.Text & "','" & txtPassword.Text & "')"
Dim cmd As OleDbCommand = New OleDbCommand(command, myconnection)
cmd.Parameters.Add(New OleDbParameter("ID", CType(txtName.Text, String)))
cmd.Parameters.Add(New OleDbParameter("Librarian Name", CType(txtStaffID.Text, String)))
cmd.Parameters.Add(New OleDbParameter("Staff ID", CType(txtPhone.Text, String)))
cmd.Parameters.Add(New OleDbParameter("Phone Number", CType(txtUsername.Text, String)))
cmd.Parameters.Add(New OleDbParameter("Username", CType(txtPassword.Text, String)))
cmd.Parameters.Add(New OleDbParameter("Password", CType(txtPassword.Text, String)))
MsgBox("Account Created")
Me.Hide()
Login.ShowDialog()
End If
Try
cmd.ExecuteNonQuery()
cmd.Dispose()
myconnection.Close()
txtName.Clear()
txtStaffID.Clear()
txtPhone.Clear()
txtUsername.Clear()
txtPassword.Clear()
Catch ex As Exception
MsgBox(ex.Message)
End Try
Your code starts out with several undeclared variables. The connection string variable can be a class level variable so it can be used in several methods. Then you open a connection that you don't use until half way down the code. Don't open connections utill directly before the .Execute.... I read a very good analogy here on Stack Overflow. Connections are like refrigerator doors. Open only when you must. Get out or put in what you need to as quickly as possible. Then close as soon as possible. You can pass the connection string directly to the constructor of the connection.
Database objects need to be disposed. Using...End Using blocks handle this for us even if there is an error. I had to guess at the data type of the parameters. Please check your database for the correct type and correct the code accordingly.
Private ConStr As String = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=D:\SEM 5\CSC301\ASSESSMENT 3\database.accdb"
Private Sub OpCode()
Dim exists As Boolean
Using con As New OleDbConnection(ConStr),
registercmd As OleDbCommand = New OleDbCommand("select * from users where
[Librarian Name]= #Name or
[Staff ID]= #StaffID or
[Phone Number]= #Phone or
[Username]= #User or
[Password]= #PWord;", con)
With registercmd.Parameters
.Add("#Name", OleDbType.VarWChar).Value = txtName.Text
.Add("#StaffID", OleDbType.VarWChar).Value = txtStaffID.Text 'Often an ID is a numeric type. Check your database.
.Add("#Phone", OleDbType.VarChar).Value = txtPhone.Text
.Add("#User", OleDbType.VarWChar).Value = txtUsername.Text
.Add("#PWord", OleDbType.VarWChar).Value = txtPassword.Text
End With
con.Open()
Using registered = registercmd.ExecuteReader
If registered.HasRows Then
exists = True
End If
End Using
End Using
If exists Then
MessageBox.Show("Account Exist!", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
Else
Using con As New OleDbConnection(ConStr),
cmd As OleDbCommand = New OleDbCommand("insert into users([Librarian Name],[Staff ID],[Phone Number],[Username],[Password])
Values(#Name, #StaffID, #Phone, #UserName, #PWord);", con)
With cmd.Parameters
.Add("#Name", OleDbType.VarWChar).Value = txtName.Text
.Add("#StaffID", OleDbType.VarWChar).Value = txtStaffID.Text
.Add("#Phone", OleDbType.VarChar).Value = txtPhone.Text
.Add("#UserName", OleDbType.VarWChar).Value = txtUsername.Text
.Add("#PWord", OleDbType.VarWChar).Value = txtPassword.Text
End With
con.Open()
cmd.ExecuteNonQuery()
End Using
MsgBox("Account Created")
Hide()
Login.ShowDialog()
End If
txtName.Clear()
txtStaffID.Clear()
txtPhone.Clear()
txtUsername.Clear()
txtPassword.Clear()
End Sub
Another bad problem that I see. Your appear to be storing passwords as plain text. All passwords should be salted and encrypted.
1st off, my apologies if this question has been asked. I have looked but haven't found an exact answer to the problem I'm facing. Secondly, I must stress that, I am not a developer, I'm an engineer and only writing sowftware as a needs must situation.
I have a form which passes data to an access db (This works). However I need to update it so that it will pass the information to different tables within the same db based upon a selection in a combobox. For instance if combobox selection = X then insert into tableX, if combobox = Y then insert into tableY. Any and all help is appreciated.
I've tried using If statements in order to select the appropriate table, but this doesn't work.
Imports System.Data.OleDb
Public Class Form1
Public ds As New DataSet
Dim provider As String
Dim dataFile As String
Dim connString As String
Dim myConnection As OleDbConnection = New OleDbConnection
Dim rs As New resizer
Dim cmd As OleDbCommand
Private con As Object
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
provider = "Provider=Microsoft.Jet.OleDb.4.0;Data Source="
dataFile = "R:\Quality\NCR-Access_Database\NCRdb1.mdb"
connString = provider & dataFile
myConnection.ConnectionString = connString
myConnection.Open()
Dim str As String
str = ""
If ComboBox2.SelectedText = "Assembly" Then
str = "Insert into [ASSEMBLYtbl]([NCR-No],[Week-No],[Part-No],[Drawing-Rev],[Description],[W/O-Number],[Operator-No],[Operation-No],[Machine-No],[Section],[Batch-Qty],[Reject_Qty],[Disposition],[Mat-Cost],[Standard-Cost],[Defect-Descripition],[Fault-Code],[Dept],[Root-Cause],[NCR-Pinksheet],[Action]) Values (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)"
ElseIf ComboBox2.SelectedText = "Grinding" Then
str = "Insert into [GRINDINGtbl]([NCR-No],[Week-No],[Part-No],[Drawing-Rev],[Description],[W/O-Number],[Operator-No],[Operation-No],[Machine-No],[Section],[Batch-Qty],[Reject_Qty],[Disposition],[Mat-Cost],[Standard-Cost],[Defect-Descripition],[Fault-Code],[Dept],[Root-Cause],[NCR-Pinksheet],[Action]) Values (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)"
ElseIf ComboBox2.SelectedText = "Milling" Then
str = "Insert into [MILLINGtbl]([NCR-No],[Week-No],[Part-No],[Drawing-Rev],[Description],[W/O-Number],[Operator-No],[Operation-No],[Machine-No],[Section],[Batch-Qty],[Reject_Qty],[Disposition],[Mat-Cost],[Standard-Cost],[Defect-Descripition],[Fault-Code],[Dept],[Root-Cause],[NCR-Pinksheet],[Action]) Values (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)"
ElseIf ComboBox2.SelectedText = "Mill-Turn" Then
str = "Insert into [MILL-TURNtbl]([NCR-No],[Week-No],[Part-No],[Drawing-Rev],[Description],[W/O-Number],[Operator-No],[Operation-No],[Machine-No],[Section],[Batch-Qty],[Reject_Qty],[Disposition],[Mat-Cost],[Standard-Cost],[Defect-Descripition],[Fault-Code],[Dept],[Root-Cause],[NCR-Pinksheet],[Action]) Values (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)"
ElseIf ComboBox2.SelectedText = "Turning" Then
str = "Insert into [TURNINGtbl]([NCR-No],[Week-No],[Part-No],[Drawing-Rev],[Description],[W/O-Number],[Operator-No],[Operation-No],[Machine-No],[Section],[Batch-Qty],[Reject_Qty],[Disposition],[Mat-Cost],[Standard-Cost],[Defect-Descripition],[Fault-Code],[Dept],[Root-Cause],[NCR-Pinksheet],[Action]) Values (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)"
ElseIf ComboBox2.SelectedText = "Supplier" Then
str = "Insert into [PURCHASINGtbl]([NCR-No],[Week-No],[Part-No],[Drawing-Rev],[Description],[W/O-Number],[Operator-No],[Operation-No],[Machine-No],[Section],[Batch-Qty],[Reject_Qty],[Disposition],[Mat-Cost],[Standard-Cost],[Defect-Descripition],[Fault-Code],[Dept],[Root-Cause],[NCR-Pinksheet],[Action]) Values (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)"
ElseIf ComboBox2.SelectedText = "Subcon" Then
str = "Insert into [PURCHASINGtbl]([NCR-No],[Week-No],[Part-No],[Drawing-Rev],[Description],[W/O-Number],[Operator-No],[Operation-No],[Machine-No],[Section],[Batch-Qty],[Reject_Qty],[Disposition],[Mat-Cost],[Standard-Cost],[Defect-Descripition],[Fault-Code],[Dept],[Root-Cause],[NCR-Pinksheet],[Action]) Values (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)"
ElseIf ComboBox2.SelectedText = "Quality" Then
str = "Insert into [QUALITYtbl]([NCR-No],[Week-No],[Part-No],[Drawing-Rev],[Description],[W/O-Number],[Operator-No],[Operation-No],[Machine-No],[Section],[Batch-Qty],[Reject_Qty],[Disposition],[Mat-Cost],[Standard-Cost],[Defect-Descripition],[Fault-Code],[Dept],[Root-Cause],[NCR-Pinksheet],[Action]) Values (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)"
End If
cmd = New OleDbCommand(str, myConnection)
cmd.Parameters.Add(New OleDbParameter("NCR-No", TextBox1.Text))
cmd.Parameters.Add(New OleDbParameter("Week-No", TextBox3.Text))
cmd.Parameters.Add(New OleDbParameter("Part-No", TextBox4.Text))
cmd.Parameters.Add(New OleDbParameter("Drawing_Rev", TextBox5.Text))
cmd.Parameters.Add(New OleDbParameter("Description", TextBox6.Text))
cmd.Parameters.Add(New OleDbParameter("W/O-No", TextBox7.Text))
cmd.Parameters.Add(New OleDbParameter("Operator-No", TextBox8.Text))
cmd.Parameters.Add(New OleDbParameter("Operation-No", TextBox9.Text))
cmd.Parameters.Add(New OleDbParameter("Machine-No", TextBox10.Text))
cmd.Parameters.Add(New OleDbParameter("Section", ComboBox2.Text))
cmd.Parameters.Add(New OleDbParameter("Batch-Qty", TextBox12.Text))
cmd.Parameters.Add(New OleDbParameter("Reject_Qty", TextBox13.Text))
cmd.Parameters.Add(New OleDbParameter("Disposition", TextBox14.Text))
cmd.Parameters.Add(New OleDbParameter("Mat-Cost", TextBox15.Text))
cmd.Parameters.Add(New OleDbParameter("Standard-Cost", TextBox16.Text))
cmd.Parameters.Add(New OleDbParameter("Defect-Description", RichTextBox1.Text))
cmd.Parameters.Add(New OleDbParameter("Fault-Code", TextBox17.Text))
cmd.Parameters.Add(New OleDbParameter("Dept", TextBox18.Text))
cmd.Parameters.Add(New OleDbParameter("Root-Cause", RichTextBox2.Text))
cmd.Parameters.Add(New OleDbParameter("NCR-Pinksheet", ComboBox1.Text))
cmd.Parameters.Add(New OleDbParameter("Permanent-Action", RichTextBox3.Text))
Try
cmd.ExecuteNonQuery()
cmd.Dispose()
myConnection.Close()
TextBox1.Clear()
TextBox4.Clear()
TextBox5.Clear()
TextBox3.Clear()
TextBox6.Clear()
TextBox7.Clear()
TextBox8.Clear()
TextBox9.Clear()
TextBox10.Clear()
ComboBox2.ResetText()
TextBox12.Clear()
TextBox13.Clear()
TextBox14.Clear()
TextBox15.Clear()
TextBox16.Clear()
RichTextBox1.Clear()
TextBox17.Clear()
TextBox18.Clear()
RichTextBox2.Clear()
ComboBox1.ResetText()
RichTextBox3.Clear()
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
End Class
When submitting I get a dialog that states "Command text was not set for the command object". If i submit again, then I get an exception unhandled event in VS --- "System.InvalidOperationException: 'Not allowed to change the 'ConnectionString' property. The connection's current state is open.'"
use INSERT INTO syntax
INSERT INTO table-name (column-names)
VALUES (values)
SQL INSERT INTO with SELECT like this
INSERT INTO Customer (FirstName, LastName, City, Country, Phone)
SELECT LEFT(ContactName, CHARINDEX(' ',ContactName) - 1),
SUBSTRING(ContactName, CHARINDEX(' ',ContactName) + 1, 100),
City, Country, Phone
FROM Supplier
WHERE CompanyName = 'casterx.co'
I am trying to execute two different INSERT statements with one click of a button.
But when I try running my code only one of the INSERT statements is working at time.
What is the best way to fix this?
pro = "Provider=Microsoft.ACE.OLEDB.12.0;data source=C:\Users\XXXX\Desktop\XXXX\XXXXX.mdb"
connstring = pro
myconnection.ConnectionString = connstring
myconnection.Open()
commmand = ("insert into ApplicationData ([lastname], [firstname],[studentbirthday],[gender], [email], [phonenumber], [address], [city], [state], [zip], [dadlastname], [dadfirstname], [momlastname],[momfirstname]) values ('" & NewLastNameText.Text & "', '" & NewFirstNameText.Text & "','" & NewDateTimePicker.Text & "','" & NewGenderText.Text & "','" & NewEmailText.Text & "','" & phone.Text & "','" & NewAddressText.Text & "','" & city.Text & "','" & state.Text & "','" & zip.Text & "','" & NewDadLNtext.Text & "','" & NewDadFNtext.Text & "','" & NewMomLNtext.Text & "','" & NewMomFNtext.Text & "')")
commmand = ("insert into StudentLogin ([username], [password]) values('" & username.Text & "','" & password.Text & "')")
Dim cmd As OleDbCommand = New OleDbCommand(commmand, myconnection)
cmd.Parameters.Add(New OleDbParameter("lastname", CType(NewLastNameText.Text, String)))
cmd.Parameters.Add(New OleDbParameter("firstname", CType(NewFirstNameText.Text, String)))
cmd.Parameters.Add(New OleDbParameter("studentbirthday", CType(NewDateTimePicker.Text, String)))
cmd.Parameters.Add(New OleDbParameter("gender", CType(NewDateTimePicker.Text, String)))
cmd.Parameters.Add(New OleDbParameter("email", CType(NewEmailText.Text, String)))
cmd.Parameters.Add(New OleDbParameter("phonenumber", CType(phone.Text, String)))
cmd.Parameters.Add(New OleDbParameter("address", CType(NewAddressText.Text, String)))
cmd.Parameters.Add(New OleDbParameter("city", CType(city.Text, String)))
cmd.Parameters.Add(New OleDbParameter("state", CType(state.Text, String)))
cmd.Parameters.Add(New OleDbParameter("zip", CType(zip.Text, String)))
cmd.Parameters.Add(New OleDbParameter("dadlastname", CType(NewDadLNtext.Text, String)))
cmd.Parameters.Add(New OleDbParameter("dadfirstname", CType(NewDadFNtext.Text, String)))
cmd.Parameters.Add(New OleDbParameter("momfirstname", CType(NewMomLNtext.Text, String)))
cmd.Parameters.Add(New OleDbParameter("momlastname", CType(NewMomFNtext.Text, String)))
cmd.Parameters.Add(New OleDbParameter("username", CType(username.Text, String)))
cmd.Parameters.Add(New OleDbParameter("password", CType(password.Text, String)))
Try
cmd.ExecuteNonQuery()
cmd.Dispose()
myconnection.Close()
MsgBox("Student Added")
NewLastNameText.Clear()
NewFirstNameText.Clear()
NewEmailText.Clear()
NewAddressText.Clear()
NewDadLNtext.Clear()
NewDadFNtext.Clear()
NewMomLNtext.Clear()
NewMomFNtext.Clear()
Catch ex As Exception
End Try
Put both commands into the same string
Dim command1 = "insert into ApplicationData ([lastname], ... values (?, ?, ...)"
Dim command2 = "insert into StudentLogin ([username], ... values (?, ?, ...)"
commmand = command1 & "; " & command2
Btw.: you are adding parameters (which is fine), but did not replace the string concatenation of the commands by parameters. For OLEDB, you have to use positional parameters. I.e., in the SQL text, you have to use a ? for each parameter. Then you have to add the parameters to the parameter collection in the same order! (The name you are using there is ignored, so it does not matter.)
Pass the connection string to the connection when creating it and do not change it afterwards. Always declare the connection in a Using Statement. It automatically closes and disposes the connection at the end. Note, it is not a problem to create new connection objects every time you use one. Because of connection pooling, the "real" connection will be reused.
pro = "Provider=Microsoft.ACE.OLEDB.12.0;data source=C:\Users\XXXX\Desktop\XXXX\XXXXX.mdb"
Using myconnection As New OleDbConnection(pro)
myconnection.Open()
Dim command1 = "insert into ApplicationData ([lastname], ... values (?, ?, ...)"
Dim command2 = "insert into StudentLogin ([username], ... values (?, ?, ...)"
commmand = command1 & "; " & command2
...
End Using ' Automatically closes connection here.
OleDb does not care about the names or our parameters. It only cares about the order they appear in the Sql statment matches the order they are added to the parameters collection.
Concatenating strings in you Sql statement is a bad idea for several reason and is certainly not needed when you are using parameters. The .Add method of the parameters collection is very clever and returns an OleDb parameter object without us having to declare on explicitly. It is always a good idea to include the OleDb data type.
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
'Pass the connection string directly to the constructor of the connection
Using cn As New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;data source=C:\Users\XXXX\Desktop\XXXX\XXXXX.mdb")
'Pass the Sql statement and the connection directly to the constructor of the command.
'Note: this should NOT be an open connection.
Using StudentCommand As New OleDbCommand("insert into ApplicationData ([lastname], [firstname],[studentbirthday],[gender], [email], [phonenumber], [address], [city], [state], [zip], [dadlastname], [dadfirstname], [momlastname],[momfirstname]) values (lastname, firstname,studentbirthday,gender,email,phonenumber,address,city,state,zip,dadlastname,dadfirstname,momlastname,momfirstname);", cn)
StudentCommand.Parameters.Add("lastname", OleDbType.VarChar).Value = NewLastNameText.Text
StudentCommand.Parameters.Add("firstname", OleDbType.VarChar).Value = NewFirstNameText.Text
StudentCommand.Parameters.Add("studentbirthday", OleDbType.VarChar).Value = NewDateTimePicker.Text
StudentCommand.Parameters.Add("gender", OleDbType.VarChar).Value = NewDateTimePicker.Text
StudentCommand.Parameters.Add("email", OleDbType.VarChar).Value = NewEmailText.Text
StudentCommand.Parameters.Add("phonenumber", OleDbType.VarChar).Value = phone.Text
StudentCommand.Parameters.Add("address", OleDbType.VarChar).Value = NewAddressText.Text
StudentCommand.Parameters.Add("city", OleDbType.VarChar).Value = city.Text
StudentCommand.Parameters.Add("state", OleDbType.VarChar).Value = state.Text
StudentCommand.Parameters.Add("zip", OleDbType.VarChar).Value = zip.Text
StudentCommand.Parameters.Add("dadlastname", OleDbType.VarChar).Value = NewDadLNtext.Text
StudentCommand.Parameters.Add("dadfirstname", OleDbType.VarChar).Value = NewDadFNtext.Text
StudentCommand.Parameters.Add("momfirstname", OleDbType.VarChar).Value = NewMomLNtext.Text
StudentCommand.Parameters.Add("momlastname", OleDbType.VarChar).Value = NewMomFNtext.Text
'Open the connection at the last minute
cn.Open()
StudentCommand.ExecuteNonQuery()
cn.Close()
End Using 'Disposes StudentCommand
Using LoginCommand As New OleDbCommand("insert into StudentLogin ([username], [password]) values(#username, #password;", cn)
LoginCommand.Parameters.Add("#username", OleDbType.VarChar).Value = username.Text
LoginCommand.Parameters.Add("#password", OleDbType.VarChar).Value = password.Text
cn.Open()
LoginCommand.ExecuteNonQuery()
'We don't need to .Close the connection
'The second End Using will close and dispose the connection
End Using 'Disposes LoginCommand
End Using
MessageBox.Show("Student Added")
NewLastNameText.Clear()
NewFirstNameText.Clear()
NewEmailText.Clear()
NewAddressText.Clear()
NewDadLNtext.Clear()
NewDadFNtext.Clear()
NewMomLNtext.Clear()
NewMomFNtext.Clear()
End Sub
One button click, 2 commands executed.
Of course in a real application you would NEVER save passwords as plain text.
I have tried to insert or update from my vb.net form into MS-Access database.
The dataset updates but the access database wont. Below is my code.
Try
Dim addLocation As String = "Insert into Provider (StateCode, Provider)" _
& "values ('" & ComboBox1.Text & "', '" & TextBox2.Text & "')"
Dim sqlcommand As New OleDbCommand
conn.Open()
With sqlcommand
.CommandText = addLocation
.Connection = conn
.ExecuteNonQuery()
End With
MsgBox("One record added", MsgBoxStyle.Information)
refreshGrid()
Catch ex As Exception
MsgBox(ex.ToString)
End Try
Private Sub refreshGrid()
cnString = "PROVIDER = Microsoft.ace.oledb.12.0;data source =" & Application.StartupPath & "\HCHPClosedIn.accdb"
sqlQRY = "SELECT * FROM Provider"
conn = New OleDbConnection(cnString)
Try
conn.Open()
da = New OleDbDataAdapter(sqlQRY, conn)
Dim cb As OleDbCommandBuilder = New OleDbCommandBuilder(da)
da.Fill(ds, "Customers")
DataGridView1.DataSource = ds
DataGridView1.DataMember = "Customers"
End Try
End Sub
Its been a while but I think I recall Access is kinda picky with commit. Try this:
With sqlcommand
.CommandText = addLocation
.Connection = conn
.ExecuteNonQuery()
.transaction = trans
End With
Trans.Commit()