how to run multiple insert query on single click in vb.net - vb.net

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();

Related

the connection string property has not been initialized. vb.net access. BELOW is the code

Try
If MsgBox("SAVE THIS ACADEMIC YEAR?", vbYesNo + vbQuestion, title) = vbYes Then
cn.Open()
cm = New OleDbCommand("update [tblay] set status = 'CLOSE'", cn)
cm.ExecuteNonQuery()
cn.Close()
cn.Open()
cm = New OleDbCommand("INSERT INTO [tblay] (aycode,year1,year2,division)values(#aycode,#year1,#year2,#division)", cn)
With cm
.Parameters.AddWithValue("aycode", txtAY.Text)
.Parameters.AddWithValue("year1", txtYear1.Text)
.Parameters.AddWithValue("year2", txtYear2.Text)
.Parameters.AddWithValue("division", cboDivision.Text)
.ExecuteNonQuery()
End With
cn.Close()
MsgBox("NEW ACADEMIC YEAR HAS BEEN SUCCESSFULLY SAVED!", vbInformation, title)
With frmAY
.LoadRecords()
End With
Clear()
End If
Catch ex As Exception
cn.Close()
MsgBox(ex.Message, vbCritical, title)
End Try
This is the code to load records:
Sub LoadRecords()
Try
DataGridView1.Rows.Clear()
Dim i As Integer
cn.Open()
cm = New OleDbCommand("select * from tblay", cn)
dr = cm.ExecuteReader
While dr.Read
i += 1
DataGridView1.Rows.Add(i, dr.Item("aycode").ToString, dr.Item("year1").ToString, dr.Item("year2").ToString, dr.Item("division").ToString, dr.Item("status").ToString)
End While
cn.Close()
Catch ex As Exception
cn.Close()
MsgBox(ex.Message, vbCritical, title)
End Try
End Sub
This might be more than you want so if so sorry.
SQLite Database (DB) CRUD function are very Boiler Plate Code. That Said I use the same process repetably.
By pacing the code in Using blocks NO need to close the DB and other functions.
I create a button for each function SAVE DELETE and UPDATE that call the function.
Here are the functions.
This code needs to be placed top level
Public connStr As String = "Data Source={0};Version=3;"
Public conn As SQLiteConnection
Here is the SAVE data NOTE the '{gv_dbName} is declared in a Module.
Private Sub InsertSiteData()
dateToday = CDate(CDate(Date.Today).ToString("M-d-yyyy"))
Using conn As New SQLiteConnection($"Data Source = '{gv_dbName}';Version=3;")
conn.Open()
Using cmd As New SQLiteCommand
cmd.Connection = conn
Try
cmd.CommandText = "INSERT INTO LinkTable (ytChannelName,ytLinkAddress,ytLastVisit,ytSiteType) VALUES (#ytChannelName,#ytLinkAddress,#ytLastVisit,#ytSiteType)"
cmd.Parameters.Add("#ytChannelName", DbType.String).Value = tbSiteName.Text.Trim
cmd.Parameters.Add("#ytLinkAddress", DbType.String).Value = tbUrl.Text.Trim
cmd.Parameters.Add("#ytLastVisit", DbType.String).Value = dateToday.ToString("M-d-yyyy")
cmd.Parameters.Add("#ytSiteType", DbType.String).Value = strType.Trim
cmd.ExecuteNonQuery()
Catch ex As Exception
MsgBox("Insert Failed")
End Try
End Using
End Using
gvTxType = ""
frmStart.Show()
Close()
End Sub
Here is the DELETE.
Private Sub DeleteSiteData()
Using conn As New SQLiteConnection($"Data Source = '{gv_dbName}';Version=3;")
conn.Open()
Using cmd As New SQLiteCommand
cmd.Connection = conn
cmd.CommandText = "DELETE FROM LinkTable WHERE LID =" & gvID
cmd.ExecuteNonQuery()
End Using
End Using
gvTxType = ""
frmStart.Show()
Close()
End Sub
And the UPDATE.
Public Sub UpdateSiteData()
dateToday = CDate(CDate(Date.Today).ToString("M-d-yyyy"))
Using conn As New SQLiteConnection($"Data Source = '{gv_dbName}';Version=3;"),
cmd As New SQLiteCommand("UPDATE LinkTable SET ytChannelName = #ytChannelName, ytLinkAddress = #ytLinkAddress ,ytLastVisit = #ytLastVisit,ytSiteType = #ytSiteType WHERE LID =" & gvID, conn)
conn.Open()
cmd.Parameters.Add("#ytChannelName", DbType.String).Value = tbSiteName.Text.Trim
cmd.Parameters.Add("#ytLinkAddress", DbType.String).Value = tbUrl.Text.Trim
cmd.Parameters.Add("#ytLastVisit", DbType.String).Value = dateToday.ToString("M-d-yyyy")
cmd.Parameters.Add("#ytSiteType", DbType.String).Value = strType.Trim
cmd.Parameters.Add("#LID", DbType.String).Value = gvID
cmd.ExecuteNonQuery()
End Using
gvTxType = ""
frmStart.Show()
Close()
End Sub

Command text was not set for the command object using vb and ms-access

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.

VB.Net/Access SQL insertion sub query issue

I am making a form that can be filled in and will execute a insertion query with a button. I do not know how to reference another table within this block of code. I am trying to insert the Name, Phone Number, and Email within the form along with the corresponding Distributor ID. The only way to get the Distributor ID is to reference the Distributor table. Anyone have any ideas? Thanks!
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
provider = 0
dataFile = 0
provider = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source="
dataFile = "XXXXXXX.mdb"
connString = provider & dataFile
myConnection.ConnectionString = connString
myConnection.Open()
'*THIS IS THE PROBLEM AREA*'
Dim str As String
str = "INSERT INTO [Distributor Contact] ([Name], [Phone Number], [Email], [Distributor ID]) VALUES(?,?,?,?) WHERE [Distributor ID] IN (SELECT DISTINCT [Distributor ID] FROM [Distributor] WHERE [Distributor Name]= '" & ComboBox_Dist.SelectedItem.ToString() & "'))"
Dim cmd As OleDbCommand = New OleDbCommand(str, myConnection)
cmd.Parameters.Add(New OleDbParameter("Name", CType(TextBox2.Text, String)))
cmd.Parameters.Add(New OleDbParameter("Phone Number", CType(TextBox3.Text, String)))
cmd.Parameters.Add(New OleDbParameter("Email", CType(TextBox4.Text, String)))
Me.Refresh()
Try
cmd.ExecuteNonQuery()
cmd.Dispose()
myConnection.Close()
TextBox2.Clear()
TextBox3.Clear()
TextBox4.Clear()
MsgBox("Contact Added")
Catch ex As Exception
MsgBox(ex.Message)
End Try
myConnection.Close()
'RE-POPULATE COMBOBOX
ComboBox_Dist.Items.Clear()
Dim connString1 As String = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source= XXXXXXXXX.mdb"
Dim con As OleDbConnection = New OleDbConnection(connString1)
Dim adapter As OleDbDataAdapter
Dim cmd2 As OleDbCommand
Dim dt As DataTable = New DataTable()
Dim sql As String = "SELECT * FROM [Distributor Contact];"
cmd2 = New OleDbCommand(sql, con)
Try
con.Open()
adapter = New OleDbDataAdapter(cmd2)
adapter.Fill(dt)
'Add Items To ComboBox
For Each row In dt.Rows
ComboBox_Dist.Items.Add(row(1))
Next
con.Close()
Catch ex As Exception
MsgBox(ex.Message)
con.Close()
End Try
End Sub
Add the ComboBox_Dist as a parameter and then use a Select instead of Values for your insertion query. The select allows you to reference the Distributor table.
cmd.Parameters.Add(New OleDbParameter("Email", CType(TextBox4.Text, String)))
cmd.Parameters.Add(New OleDbParameter("DistributorName", ComboBox_Dist.SelectedItem.ToString()))
str = "INSERT INTO [Distributor Contact] ([Name], [Phone Number], [Email], [Distributor ID]) "
str += "SELECT ?,?,?, [Distributor].[DistributorID] "
str += "FROM [Distributor] WHERE [Distributor].[Distributor Name] = ?"
Here is the final working code for anyone in the future.
provider = 0
dataFile = 0
provider = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source="
dataFile = "XXXXXXXX.mdb"
connString = provider & dataFile
Dim str As String
str = "INSERT INTO [Distributor Contact] ([Contact Name], [Phone Number], [Email], [Distributor ID])"
str += "SELECT ?,?,?,[Distributor].[Distributor ID]"
str += "FROM [Distributor] WHERE [Distributor].[Distributor Name] = ?"
Dim cmd As OleDbCommand = New OleDbCommand(str, myConnection)
cmd.Parameters.Add(New OleDbParameter("Contact Name", CType(TextBox2.Text, String)))
cmd.Parameters.Add(New OleDbParameter("Phone Number", CType(TextBox3.Text, String)))
cmd.Parameters.Add(New OleDbParameter("Email", CType(TextBox4.Text, String)))
cmd.Parameters.Add(New OleDbParameter("Distributor Name", ComboBox_Dist.SelectedItem.ToString()))
Me.Refresh()

VB.net sql table not showing last rows

What I am doing-
Importing 406 rows into 5 sql tables from excel sheet.
After import, I am manually saving data one by one into each of the 5
tables on button click event and displaying on datagridview..
After saving each record, I am refreshing datagridview.
My problem -
Records are getting saved properly, but datagridview shows only
408 records, where actual no. of records are 412.
When viewed from server explorer also, only 408 records are
shown.
But table properties show that there are 412 rows.
This problem is with only first table.
my code:-
cmd.CommandText = String.Empty
cmd.Parameters.Clear()
cmd.CommandText = "INSERT into pd([Adm No],[DOA],[Name],[Course],[Fees Due],[Concession],[Contact No 1]," & _
"[Contact No 2],[E-Mail],[Year of Passing],[Address],[DOB],[College])" & _
" values(#admno,#doa,#name,#course,#totalfees,#concession,#contactno1,#contactno2,#email,#yop," & _
"#address,#dob,#college)"
cmd.Parameters.AddWithValue("#admno", i.ToString)
cmd.Parameters.AddWithValue("#doa", date_format.format_date(doa.Value.Date))
cmd.Parameters.AddWithValue("#name", txt_name.Text)
cmd.Parameters.AddWithValue("#course", combo_course.SelectedItem.ToString)
cmd.Parameters.AddWithValue("#totalfees", txt_totalfees.Text)
cmd.Parameters.AddWithValue("#concession", txt_concession.Text)
cmd.Parameters.AddWithValue("#contactno1", txt_contact1.Text)
cmd.Parameters.AddWithValue("#contactno2", txt_contact2.Text)
cmd.Parameters.AddWithValue("#email", txt_email.Text)
cmd.Parameters.AddWithValue("#yop", txt_yop.Text)
cmd.Parameters.AddWithValue("#address", txt_address.Text)
cmd.Parameters.AddWithValue("#dob", date_format.format_date(dob.Value.Date))
cmd.Parameters.AddWithValue("#college", txt_college.Text)
If con.State = ConnectionState.Closed Then
con.Open()
End If
cmd.Connection = con
cmd.ExecuteNonQuery()
'save fees details
cmd.CommandText = String.Empty
cmd.Parameters.Clear()
cmd.CommandText = "INSERT into fees([Adm No],[Name],[Fees Due],[Fees Paid],[No of Installments]," & _
"[Installment Amounts],[Receipt Nos],[Dates of Transaction],[Mode],[Bank],[Due Date]" & _
",[Total Fees],[Concession],[Cheque No],[Course])" & _
" values(#admno,#name,#feesdue,#feespaid,#noi,#instamnt,#rcno,#dot,#mode,#bank,#dd," & _
"#total,#concession,#chqno,#course)"
cmd.Parameters.AddWithValue("#admno", i.ToString)
cmd.Parameters.AddWithValue("#name", txt_name.Text)
cmd.Parameters.AddWithValue("#feesdue", (CInt(txt_totalfees.Text) - CInt(txt_concession.Text)))
cmd.Parameters.AddWithValue("#feespaid", CInt(0))
cmd.Parameters.AddWithValue("#noi", CInt(0))
cmd.Parameters.AddWithValue("#instamnt", "")
cmd.Parameters.AddWithValue("#rcno", "")
cmd.Parameters.AddWithValue("#dot", "")
cmd.Parameters.AddWithValue("#mode", "")
cmd.Parameters.AddWithValue("#bank", "")
cmd.Parameters.AddWithValue("#dd", "")
cmd.Parameters.AddWithValue("#total", CInt(txt_totalfees.Text))
cmd.Parameters.AddWithValue("#concession", txt_concession.Text)
cmd.Parameters.AddWithValue("#chqno", "")
cmd.Parameters.AddWithValue("#course", combo_course.SelectedItem.ToString)
If con.State = ConnectionState.Closed Then
con.Open()
End If
cmd.Connection = con
cmd.ExecuteNonQuery()
'save photo
If Not PictureBox1.Image Is Nothing Then
cmd.CommandText = String.Empty
cmd.Parameters.Clear()
cmd.CommandText = "Insert into img values(#adm,#name,#imge)"
Dim para As New SqlCeParameter("imge", SqlDbType.Image)
Dim ms As New MemoryStream
PictureBox1.BackgroundImage.Save(ms, PictureBox1.BackgroundImage.RawFormat)
Dim data As Byte() = ms.GetBuffer
para.Value = data
cmd.Parameters.AddWithValue("#adm", lb_admno.Text)
cmd.Parameters.AddWithValue("#name", txt_name.Text)
cmd.Parameters.Add(para)
If con.State = ConnectionState.Closed Then
con.Open()
End If
cmd.Connection = con
cmd.ExecuteNonQuery()
Else
cmd.CommandText = String.Empty
cmd.Parameters.Clear()
cmd.CommandText = "Insert into img values(#adm,#name,#imge)"
Dim para As New SqlCeParameter("imge", SqlDbType.Image)
Dim ms As New MemoryStream
PictureBox1.BackgroundImage.Save(ms, PictureBox1.BackgroundImage.RawFormat)
Dim data As Byte() = ms.GetBuffer
para.Value = data
cmd.Parameters.AddWithValue("#adm", lb_admno.Text)
cmd.Parameters.AddWithValue("#name", txt_name.Text)
cmd.Parameters.Add(para)
If con.State = ConnectionState.Closed Then
con.Open()
End If
cmd.Connection = con
cmd.ExecuteNonQuery()
End If
cmd.CommandText = String.Empty
cmd.Parameters.Clear()
cmd.CommandText = "insert into attend values(#adm,#name,#course,#dt,#stat)"
cmd.Parameters.AddWithValue("#adm", lb_admno.Text)
cmd.Parameters.AddWithValue("#name", txt_name.Text)
cmd.Parameters.AddWithValue("#course", combo_course.SelectedItem.ToString)
cmd.Parameters.AddWithValue("#dt", "")
cmd.Parameters.AddWithValue("#stat", "")
If con.State = ConnectionState.Closed Then
con.Open()
End If
cmd.Connection = con
cmd.ExecuteNonQuery()
cmd.CommandText = String.Empty
cmd.Parameters.Clear()
cmd.CommandText = "insert into testdb values(#adm,#name,#course,#tname,#tdate,#marksob,#marksout)"
cmd.Parameters.AddWithValue("#adm", lb_admno.Text)
cmd.Parameters.AddWithValue("#name", txt_name.Text)
cmd.Parameters.AddWithValue("#course", combo_course.SelectedItem.ToString)
cmd.Parameters.AddWithValue("#tname", "")
cmd.Parameters.AddWithValue("#tdate", "")
cmd.Parameters.AddWithValue("#marksob", "")
cmd.Parameters.AddWithValue("#marksout", "")
If con.State = ConnectionState.Closed Then
con.Open()
End If
cmd.Connection = con
cmd.ExecuteNonQuery()
problem was in the code of importing records. I was reading cells of excel file and inserting them into five tables.
Problem arises only if I import records in all five tables one by one, but if I import records into only three tables then the problem doesn't arise.
This solved my problem, but I didn't happen to know the actual reason behind it. Why can't I import records into five tables one after another? If anyone finds the reason behind the error please comment.

Insert multiple rows in access database using oledb parameters

I am trying to insert multiple rows in a listitems to a database using parameters.
But it won't give me any errors, and also won't insert any data in the table.
does anyone have any ideas on this one?
strSQL = "insert into tbltrans2 (transid,itemcode,itemname,qty,price,[total],btw) values ( ?,?,?,?,?,?,?)"
Using cn As New OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + Application.StartupPath + "\\POS.mdb"), _
cmd As New OleDbCommand(strSQL, cn)
cmd.Parameters.Add("?", OleDbType.VarChar).Value = txtTransId.Text
cmd.Parameters.Add("?", OleDbType.VarChar, 10)
cmd.Parameters.Add("?", OleDbType.VarChar, 50)
cmd.Parameters.Add("?", OleDbType.Integer)
cmd.Parameters.Add("?", OleDbType.Decimal)
cmd.Parameters.Add("?", OleDbType.Decimal)
cmd.Parameters.Add("?", OleDbType.VarChar, 50)
cn.Open()
For Each ls As ListViewItem In ListItems.Items
cmd.Parameters(1).Value = ls.Tag
cmd.Parameters(2).Value = ls.SubItems(0).Text
cmd.Parameters(3).Value = Integer.Parse(ls.SubItems(1).Text)
cmd.Parameters(4).Value = Decimal.Parse(ls.SubItems(2).Text)
cmd.Parameters(5).Value = Decimal.Parse(ls.SubItems(3).Text)
cmd.Parameters(6).Value = ls.SubItems(5).Text
Next ls
End Using
Hey steve, When I try that, it gives me 'syntax error in update statement' erro. Here is my code:
Try
strSQL = "UPDATE set instock = ? where itemcode= ?"
Using cn As New OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + Application.StartupPath + "\\POS.mdb"), _
cmd As New OleDbCommand(strSQL, cn)
cn.Open()
For Each ls As ListViewItem In ListItems.Items
cmd.Parameters.Add("?", OleDbType.Integer).Value = 100
cmd.Parameters.Add("?", OleDbType.VarChar).Value = ls.Tag
cmd.ExecuteNonQuery()
Next ls
cn.Close()
End Using
Catch ex As Exception
MsgBox(ex.Message)
End Try
Now, I still need help with decreasing the stock. Here is the code that I use, but it isn't working.
strSQL = "UPDATE tblitem set instock ='instock'- ? where itemcode = ?"
Using cn As New OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + Application.StartupPath + "\\POS.mdb"), _
cmd As New OleDbCommand(strSQL, cn)
cn.Open()
For Each ls As ListViewItem In SalesListItems.Items
If Not (ls.SubItems(1).Tag(0) = "n") Then
cmd.Parameters.Add("?", OleDbType.Integer).Value = ls.SubItems(1).Text
cmd.Parameters.Add("?", OleDbType.VarChar, 10).Value = ls.Tag
cmd.ExecuteNonQuery()
End If
Next ls
cn.Close()
End Using
You are missing the execute part
For Each ls As ListViewItem In ListItems.Items
cmd.Parameters(1).Value = ls.Tag
cmd.Parameters(2).Value = ls.SubItems(0).Text
cmd.Parameters(3).Value = Integer.Parse(ls.SubItems(1).Text)
cmd.Parameters(4).Value = Decimal.Parse(ls.SubItems(2).Text)
cmd.Parameters(5).Value = Decimal.Parse(ls.SubItems(3).Text)
cmd.Parameters(6).Value = ls.SubItems(5).Text
cmd.ExecuteNonQuery()
Next ls
Also, are you certain on the input values coming from the subitems? If there isn't a control on their effective numeric value when you add them to the ListView, then the loop could fail with an exception when you try to convert the supposed numeric value with Parse.
EDIT: This instead for an update
strSQL = "UPDATE tblitem set instock = ? where itemcode= ?"
Using cn As New OleDbConnection("......")
cmd As New OleDbCommand(strSQL, cn)
cmd.Parameters.Add("?", OleDbType.Integer).Value = 100
cmd.Parameters.Add("?", OleDbType.VarChar).Value = yourItemCodeValue
cmd.ExecuteNonQuery()
End Using
Keep in mind that I suppose instock is a integer data type and itemcode a varchar.