The right way to save 2 table to access database in vb,net - vb.net

I tried to save all of records of 2 tables to Access database. My idea is save first table then save next table. But I think it isn't the right way when save multi tables to access because It take a long time.
Here is my code and it run ok but I don't know is there another ways which better to save multi tables to access.
Private Sub btnSave_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSave.Click
cnn.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=D:\1_Project\Project_of_VB_Net\AccessDatabase\StudentDatabase.accdb"
cmd.Connection = cnn
Dim cmdupdate As String
Dim cmdinsert As String
For Each dr In dt.Rows
cmdupdate = "UPDATE StudentData SET ID=#ID, StudentName=#StudentName, StudentID=#StudentID, StudentClass=#StudentClass WHERE StudentID=#StudentID"
cmdinsert = "INSERT INTO StudentData(ID,StudentName,StudentID,StudentClass) VALUES(#ID,#StudentName,#StudentID,#StudentClass)"
cmd.Parameters.Clear()
cmd.CommandText = cmdupdate
cmd.Parameters.AddWithValue("#ID", dr("ID"))
cmd.Parameters.AddWithValue("#StudentName", dr("StudentName"))
cmd.Parameters.AddWithValue("#StudentID", dr("StudentID"))
cmd.Parameters.AddWithValue("#StudentClass", dr("StudentClass"))
cnn.Open()
Dim count = cmd.ExecuteNonQuery()
If count = 0 Then
cmd.CommandText = cmdinsert
cmd.ExecuteNonQuery()
End If
cnn.Close()
Next
For Each dr2 In dt2.Rows
cmdupdate = "UPDATE StudentData2 SET ID2=#ID2, StudentName2=#StudentName2, StudentID2=#StudentID2, StudentClass2=#StudentClass2 WHERE StudentID2=#StudentID2"
cmdinsert = "INSERT INTO StudentData2(ID2,StudentName2,StudentID2,StudentClass2) VALUES(#ID2,#StudentName2,#StudentID2,#StudentClass2)"
cmd.Parameters.Clear()
cmd.CommandText = cmdupdate
cmd.Parameters.AddWithValue("#ID2", dr2("ID2"))
cmd.Parameters.AddWithValue("#StudentName2", dr2("StudentName2"))
cmd.Parameters.AddWithValue("#StudentID2", dr2("StudentID2"))
cmd.Parameters.AddWithValue("#StudentClass2", dr2("StudentClass2"))
cnn.Open()
Dim count2 = cmd.ExecuteNonQuery()
If count2 = 0 Then
cmd.CommandText = cmdinsert
cmd.ExecuteNonQuery()
End If
cnn.Close()
Next
End Sub

Related

Database locked in vb.net when trying to update data in vb.net

Hello I have a simple method to update customer details in one of my database tables however when i try to update it an error occurs saying the database is locked. I have no idea how to fix this because my add and delete queries work just fine.
This is the error message:
System.Data.SQLite.SQLiteException: 'database is locked
database is locked'
Public Sub updateguest(ByVal sql As String)
Try
con.Open()
With cmd
.CommandText = sql
.Connection = con
End With
result = cmd.ExecuteNonQuery
If result > 0 Then
MsgBox("NEW RECORD HAS BEEN UPDATED!")
con.Close()
Else
MsgBox("NO RECORD HASS BEEN UPDATDD!")
End If
Catch ex As Exception
MsgBox(ex.Message)
Finally
con.Close()
End Try
End Sub
Private Sub IbtnUpdate_Click(sender As Object, e As EventArgs) Handles ibtnUpdate.Click
Dim usql As String = "UPDATE Customers SET fname = '" & txtFName.Text & "'" & "WHERE CustomerID ='" & txtSearchID.Text & "'"
updateguest(usql)
End Sub
Private Sub IbtnSearch_Click(sender As Object, e As EventArgs) Handles ibtnSearch.Click
Dim sSQL As String
Dim newds As New DataSet
Dim newdt As New DataTable
Dim msql, msql1 As String
Dim con As New SQLiteConnection(ConnectionString)
con.Open()
msql = "SELECT * FROM Customers Where Fname Like '" & txtSearchName.Text & "%'"
msql1 = "SELECT * FROM Customers Where CustomerID '" & txtSearchID.Text & "'"
Dim cmd As New SQLiteCommand(msql, con)
Dim cmd1 As New SQLiteCommand(msql1, con)
Dim dt = GetSearchResults(txtSearchName.Text)
dgvCustomerInfo.DataSource = dt
Dim mdr As SQLiteDataReader = cmd.ExecuteReader()
If mdr.Read() Then
If txtSearchName.Text <> "" Then
sSQL = "SELECT * FROM customers WHERE fname LIKE'" & txtSearchName.Text & "%'"
Dim con1 As New SQLiteConnection(ConnectionString)
Dim cmd2 As New SQLiteCommand(sSQL, con1)
con1.Open()
Dim da As New SQLiteDataAdapter(cmd2)
da.Fill(newds, "customers")
newdt = newds.Tables(0)
If newdt.Rows.Count > 0 Then
ToTextbox(newdt)
End If
dgvCustomerInfo.DataSource = newdt
con1.Close()
txtSearchID.Clear()
ElseIf txtSearchID.Text <> "" Then
sSQL = "SELECT * FROM customers WHERE CustomerID ='" & txtSearchID.Text & "'"
Dim con2 As New SQLiteConnection(ConnectionString)
Dim cmd2 As New SQLiteCommand(sSQL, con2)
con2.Open()
Dim da As New SQLiteDataAdapter(cmd2)
da.Fill(newds, "customers")
newdt = newds.Tables(0)
If newdt.Rows.Count > 0 Then
ToTextbox(newdt)
End If
dgvCustomerInfo.DataSource = newdt
con2.Close()
txtSearchName.Clear()
End If
Else
MsgBox("No data found")
End If
End Sub
Private Sub IbtnDelete_Click(sender As Object, e As EventArgs) Handles ibtnDelete.Click
Dim dsql As String = "DELETE FROM customers WHERE customerid = " & txtSearchID.Text & ""
deleteme(dsql)
updatedgv(dgvCustomerInfo)
txtSearchID.Clear()
txtSearchName.Clear()
End Sub
Public Sub deleteme(ByVal sql As String)
Try
con.Open()
With cmd
.CommandText = sql
.Connection = con
End With
result = cmd.ExecuteNonQuery
If result > 0 Then
MsgBox("NEW RECORD HAS BEEN DELTED!")
con.Close()
Else
MsgBox("NO RECORD HASS BEEN DELTED!")
End If
Catch ex As Exception
MsgBox(ex.Message)
Finally
con.Close()
End Try
End Sub
You made a good start on keeping your database code separate from you user interface code. However, any message boxes should be shown in the user interface and any sql statements should be written in the data access code.
I used Using...End Using blocks to ensure that database objects are closed and disposed. I used parameters to protect against sql injection. I am not too sure of the mapping of DbType types to Sqlite types. You might have to fool with that a bit. In you original Update statement you had the ID value in quotes. This would pass a string. When you use parameters, you don't have to worry about that or ampersands and double quotes. Just one clean string.
Private ConStr As String = "Your connection string"
Public Function updateguest(FirstName As String, ID As Integer) As Integer
Dim Result As Integer
Dim usql As String = "UPDATE Customers SET fname = #fname WHERE CustomerID = #ID;"
Using con As New SQLiteConnection(ConStr),
cmd As New SQLiteCommand(usql, con)
cmd.Parameters.Add("#fname", DbType.String).Value = FirstName
cmd.Parameters.Add("#ID", DbType.Int32).Value = ID
con.Open()
Result = cmd.ExecuteNonQuery
End Using
Return Result
End Function
Private Sub IbtnUpdate_Click(sender As Object, e As EventArgs) Handles ibtnUpdate.Click
Try
Dim Result = updateguest(txtFName.Text, CInt(txtSearchID.Text))
If Result > 0 Then
MsgBox("New RECORD HAS BEEN UPDATED!")
Else
MsgBox("NO RECORD HAS BEEN UPDATDD!")
End If
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub

insert or update with single button in vb.net

how to insert and update data in database(sql server) with single button in vb.net i tried but not get the result.
here is my code.......
Private Sub Button5_Click(sender As System.Object, e As System.EventArgs) Handles Button5.Click
Try
Dim reader As SqlDataReader
Dim query As String
Dim n As Integer
n = 0
sqlcom1 = New SqlCommand("select * from mydatabase.masters")
sqlcom1.ExecuteReader()
sqlcom = New SqlCommand("select * from mydatabase.masters")
sqlcom.ExecuteReader()
reader = sqlcom1.ExecuteReader
reader = sqlcom.ExecuteReader
sqlcom = New SqlCommand("Update masters SET EmpName=#EmpName, Age=#Age, Address=#Address where Empid=#Empid", conn)
sqlcom.Parameters.Add("#EmpName", SqlDbType.VarChar).Value = TextBox4.Text
sqlcom.Parameters.Add("#Age", SqlDbType.Int).Value = TextBox3.Text
sqlcom.Parameters.Add("#Address", SqlDbType.VarChar).Value = TextBox2.Text
sqlcom.Parameters.Add("#Empid", SqlDbType.Int).Value = TextBox1.Text
sqlcom1 = New SqlCommand("insert into masters(Empid, EmpName, Age, Address) values(#Empid, #EmpName, #Age, #Address)", conn)
sqlcom1.Parameters.AddWithValue("#Empid", TextBox1.Text)
sqlcom1.Parameters.AddWithValue("#EmpName", TextBox4.Text)
sqlcom1.Parameters.AddWithValue("#Age", TextBox3.Text)
sqlcom1.Parameters.AddWithValue("#Address", TextBox2.Text)
conn.Open()
While reader.Read
n = n + 1
End While
If table.Rows.Count = n Then
sqlcom1.ExecuteNonQuery()
ElseIf table.Rows.Count = n + 1 Then
sqlcom.ExecuteNonQuery()
End If
Catch ex As Exception
MessageBox.Show("error" + ex.Message)
End Try
End Sub
Using block ensures that your connection object is closed and disposed even if there is an error.
Normally I put comments in line but the code got so cluttered that had to move most of them up here. I hope you can figure out where they belong.
Dim reader As SqlDataReader - Unused
Dim query As String - Unused
Integers are automatically initialized to zero
Pass the query and the connection to the constructor of the command.
Your connection string will tell SQL Server what database to use. It is not necessary in the query.
Apparently all you want is the count, not all the data.
This query is exactly the same as sqlcom1
Dim sqlcom As New SqlCommand("select * from mydatabase.masters", cn)
sqlcom.ExecuteReader()
You did this twice
reader = sqlcom1.ExecuteReader
Not necessay, we already retrieved the count
`While reader.Read
n = n + 1
End While`
I made the assumption that table was a DataTable populated at some other time. Using the count as comparison to the count in the table is not a great way to determine if the command is Insert or Update but it might work as long as database and table were not used with a DataAdapter that updated the database.
Private Sub Button5_Click(sender As System.Object, e As System.EventArgs) Handles Button5.Click
Try
Dim n As Integer
Using cn As New SqlConnection("Your connection string")
Dim sqlcom1 As New SqlCommand("select Count(*) from masters", cn)
cn.Open()
n = CInt(sqlcom1.ExecuteScalar) 'n is now the number of rows in the database table
Dim sqlcom As New SqlCommand
sqlcom.Parameters.Add("#EmpName", SqlDbType.VarChar).Value = TextBox4.Text
'Age is not a good idea to enter in a database. It changes over time.
'Enter the birth date and calculate the age as needed.
sqlcom.Parameters.Add("#Age", SqlDbType.Int).Value = CInt(TextBox3.Text)
sqlcom.Parameters.Add("#Address", SqlDbType.VarChar).Value = TextBox2.Text
If table.Rows.Count > n Then
'Normally EmpId would be an auto increment (identity) field
'and would NOT be included in an insert.
sqlcom.CommandText = "insert into masters(EmpName, Age, Address) values(#EmpName, #Age, #Address)"
Else
sqlcom.CommandText = "Update masters SET EmpName=#EmpName, Age=#Age, Address=#Address where Empid=#Empid"
sqlcom1.Parameters.Add("#Empid", SqlDbType.Int).Value = CInt(TextBox1.Text)
End If
sqlcom.ExecuteNonQuery()
End Using
Catch ex As Exception
MessageBox.Show("error" + ex.Message)
End Try
End Sub
On second thought, forget the whole thing. Use a DataGridView and a DataAdapter. Then you can just use Update and it will update, insert and delete.

how to insert multiple records in Access database using VB.NET

I am trying learn how to use Access within VB.NET so i tried to make a simple application using an Access Database that can be used as a dictionary where someone can add some words int the database and then he can search for them.
My db contains two tables one with Word | Description and another one with Word | Synonym
The issue is that one word may have more than one Synonyms so i was thinking i could type all the synonyms in a textbox and using Regex.Split(" ") to split them and insert them in a loop. Can this be done with OleDbParameters?
This is what i have done so far but it only inserts the last record:
str = "insert into Synonyms ([Word],[Synonym]) values (#word,#synonym)"
cmd = New OleDbCommand(str, myConnection)
cmd.Parameters.Add(New OleDbParameter("Word", CType(txtWord.Text,
String)))
cmd.Parameters.Add("#synonym", OleDbType.VarChar)
Dim syn As String() = Regex.Split(txtSynonyms.Text, " ")
Dim i As Integer = 0
While i < syn.Length()
cmd.Parameters("#synonym").Value = syn(i)
i = i + 1
End While
Try
cmd.ExecuteNonQuery()
cmd.Dispose()
MsgBox("Synonyms for word """ & txtWord.Text & """ added")
txtWord.Clear()
txtSynonyms.Clear()
Catch ex As Exception
MsgBox(ex.Message)
End Try
myConnection.Open()
While i < syn.Length()
cmd.Parameters("#synonym").Value = syn(i)
cmd.ExecuteNonQuery()
i = i + 1
End While
myConnection.Close()
Maybe you will find this helpful.
Imports System.Data.OleDb
Public Class Form1
Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
Dim con As New OleDb.OleDbConnection
Dim dbprovider As String
Dim dbsource As String
Dim ds As New DataSet
Dim da As OleDb.OleDbDataAdapter
Dim sql As String
Dim inc As Integer
dbprovider = "Provider=Microsoft.ACE.OLEDB.12.0;"
dbsource = "Data Source = C:\your_path_here\Nwind_Sample.accdb"
con.ConnectionString = dbprovider & dbsource
con.Open()
sql = "SELECT * FROM [OrderDetails]"
da = New OleDb.OleDbDataAdapter(sql, con)
da.Fill(ds, "OrderDetails")
Dim builder As New OleDbCommandBuilder(da)
Dim dsnewrow As DataRow
dsnewrow = ds.Tables("OrderDetails").NewRow()
dsnewrow.Item(0) = OrderID.Text
dsnewrow.Item(1) = ProductID.Text
dsnewrow.Item(2) = UnitPrice.Text
dsnewrow.Item(3) = Quantity.Text
dsnewrow.Item(4) = Discount.Text
'dsnewrow.Item(6) = True
ds.Tables("OrderDetails").Rows.Add(dsnewrow)
da.Update(ds, "OrderDetails")
End Sub
End Class

vb.net message: no value given for one or more required parameters

I made a POS project but when i save the data to access database the error is shown:
no value given for one or more required parameters.
My code is:
Private Sub Button3_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button3.Click
Dim MyConnection As OleDb.OleDbConnection = Nothing
Dim MyTransaction As OleDb.OleDbTransaction = Nothing
Try
'create the connection and transaction object
MyConnection = New OleDb.OleDbConnection(My.Settings.dbConnectionString)
MyConnection.Open()
MyTransaction = MyConnection.BeginTransaction
'insert the new recipt
Dim SQL As String = "insert into recipts (ReciptDate, ReciptTotal) values (:0,:1)"
Dim CMD1 As New OleDb.OleDbCommand
CMD1.Connection = MyConnection
CMD1.Transaction = MyTransaction
CMD1.CommandText = SQL
CMD1.Parameters.AddWithValue(":0", Now.Date)
CMD1.Parameters.AddWithValue(":1", TextBox4.Text)
CMD1.ExecuteNonQuery()
CMD1.Dispose()
'get the id for the recipt
SQL = "Select max (reciptId) as MAXID from recipts"
Dim CMD2 As New OleDb.OleDbCommand
CMD2.Connection = MyConnection
CMD2.Transaction = MyTransaction
CMD2.CommandText = SQL
Dim ReciptID As Long = CMD2.ExecuteScalar()
CMD2.Dispose()
'insert the details of the recipt
Dim I As Integer
For I = 0 To DGV2.Rows.Count - 1
'get the values
Dim Barcode As String = DGV2.Rows(I).Cells(0).Value
Dim BuyPrice As Decimal = DGV2.Rows(I).Cells(2).Value
Dim SellPrice As Decimal = DGV2.Rows(I).Cells(3).Value
Dim ItemCount As Integer = DGV2.Rows(I).Cells(4).Value
'next create a command
Dim CMD3 As New OleDb.OleDbCommand
SQL = "insert into ReciptDetails" & _
"(ReciptId, Barcode,ItemCount,ItemBuyPrice,ItemSellPrice)" & _
"Values" & _
"(:0 ,:1 ,:2 ,:3 ,:4)"
CMD3.Connection = MyConnection
CMD3.Transaction = Mytransaction
CMD3.CommandText = SQL
CMD1.Parameters.AddWithValue(":0", ReciptID)
CMD1.Parameters.AddWithValue(":1", Barcode)
CMD1.Parameters.AddWithValue(":2", ItemCount)
CMD1.Parameters.AddWithValue(":3", BuyPrice)
CMD1.Parameters.AddWithValue(":4", SellPrice)
CMD3.ExecuteNonQuery()
CMD3.Dispose()
Next
'all well save the changes
Mytransaction.Commit()
'close conncetion
Mytransaction.Dispose()
MyConnection.Close()
MyConnection.Dispose()
DGV2.Rows.Clear()
TextBox4.Text = ""
Catch ex As Exception
If Mytransaction IsNot Nothing Then
Mytransaction.Rollback()
End If
If MyConnection IsNot Nothing Then
If MyConnection.State = ConnectionState.Open Then
MyConnection.Close()
End If
End If
MsgBox(ex.Message, MsgBoxStyle.Critical Or MsgBoxStyle.OkOnly)
End Try
End Sub
What is the problem here?
Simple typo. In your CMD3 you're adding all the parameters to CMD1
Hence CMD3 has 5 missing parameters.

Update a Single cell of a database table in VB.net

I am using MS Access Database. Now I have to update a particular cell value. Here is my code:
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim str As String
Dim Presc As New System.Text.StringBuilder
Dim prs As String(), j As Integer
prs = Split(txtPrescription.Text, vbCrLf)
For j = 0 To prs.Length - 1
Presc.Append(prs(j))
Presc.Append(",")
Next
Try
str = Trim(lsvCase.SelectedItems(0).Text)
'MessageBox.Show(str)
Dim con As System.Data.OleDb.OleDbConnection
Dim ds As New DataSet
Dim rea As System.Data.OleDb.OleDbDataReader
con = New OleDb.OleDbConnection
Dim da As New System.Data.OleDb.OleDbDataAdapter
con.ConnectionString = "Provider = Microsoft.ACE.OLEDB.12.0; Data Source= F:\Sowmya Laptop Backups\sowdb1.accdb;"
con.Open()
Dim cmd As OleDb.OleDbCommand = con.CreateCommand
cmd.CommandText = "UPDATE Casehistory set Prescription =' " & Presc.ToString() & "'"
rea = cmd.ExecuteReader
cmd.ExecuteNonQuery()
da.FillSchema(ds, SchemaType.Mapped)
da.Update(ds, "Casehistory")
con.Close()
Catch ex As Exception
Finally
End Try
End Sub
This code updates all the cells in that column. I want to update only the particular cell having Case_ID = str
Where I have to add the WHERE clause (WHERE Case_ID = " & str & "
I would use command parameters, neater and prevents the SQL injection issue. Something like:
cmd.CommandText = "UPDATE Casehistory set Prescription =#Presc WHERE Case_ID = #CaseID"
cmd.Parameters.AddWithValue("#Presc", Presc.ToString())
cmd.Parameters.AddWithValue("#CaseID",str)
As an aside, having all this code in the button click event is less than ideal. You might want to investigate structuring your app in a more maintainable way - perhaps with a Data Layer for example.
The Where clause should be appended to the end of the OleDbCommmand.CommandText, where you define the Update statement.