how to insert multiple records in Access database using VB.NET - 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

Related

How to update access db by editing datagridview cells?

Im trying to edit items after inserting to access by clicking the save button? How can i save the edits done in datagridview rows to access?
Already tried the update query
For each loop
vb.net
Private Sub BunifuFlatButton1_Click(sender As Object, e As EventArgs) Handles BunifuFlatButton1.Click
Dim constring As String = ("Provider=Microsoft.ACE.OLEDB.12.0;Data Source= C:\Users\PU-IMO\Desktop\BlueWavesIS - Copy\BlueWavesIS\BlueWavesIS.accdb")
Dim conn As New OleDbConnection(constring)
For Each row As DataGridViewRow In DataGridView1.Rows
Using con As New OleDbConnection(constring)
'nettxt.Text = (grosstxt.Text * perdistxt.Text / 100) - (dislctxt.Text + disusd.Text + distax.Text)
Dim cmd As New OleDbCommand("Update PurchaseInvoice set [Itemnum] = #ItemNum, [Itemname]= #ItemName, [Itemqty]= #ItemQty, [Itemprice] = #ItemPrice, [discount] =#discount, [subtotal] = #subtotal,[Preference] = " & preftxt.Text & ", [Suppnum] = " & pnumtxt.Text & ", [UniqueID] = " & pautotxt.Text & " Where [UniqueID] = " & pautotxt.Text & "", con)
cmd.Parameters.AddWithValue("#ItemID", row.Cells("ItemID").Value)
cmd.Parameters.AddWithValue("#ItemName", row.Cells("ItemName").Value)
cmd.Parameters.AddWithValue("#ItemQty", row.Cells("ItemQty").Value)
cmd.Parameters.AddWithValue("#ItemPrice", row.Cells("ItemPrice").Value)
cmd.Parameters.AddWithValue("#discount", row.Cells("discount").Value)
cmd.Parameters.AddWithValue("#subtotal", row.Cells("subtotal").Value)
cmd.Parameters.AddWithValue("#Ref", preftxt.Text.ToString)
cmd.Parameters.AddWithValue("#Suppnum", Convert.ToInt32(pnumtxt.Text))
cmd.Parameters.AddWithValue("#UniqueID", Convert.ToInt32(pautotxt.Text))
DataGridView1.AllowUserToAddRows = False
con.Open()
cmd.ExecuteNonQuery()
con.Close()
End Using
Next
'This the code i used to show the data in datagridview:
Private Sub NewPurchaseInvoice_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim con As New OleDbConnection
con.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source= C:\Users\PU-IMO\Desktop\BlueWavesIS - Copy\BlueWavesIS\BlueWavesIS.accdb"
con.Open()
Dim sql As String = "Select [Itemnum],[Itemname],[Itemprice],[ItemQty],[discount],[subtotal] from PurchaseInvoice where [UniqueID] = " & pautotxt.Text & ""
Dim cmd10 As OleDbCommand = New OleDbCommand(Sql, con)
'Dim adap As New OleDbDataAdapter("Select [Itemnum],[Itemname],[Itemprice],[discount],[subtotal] from PurchaseInvoice where UniqueID = " & pautotxt.Text & "", con)
'Dim ds As New System.Data.DataSet
'adap.Fill(ds, "PurchaseInvoice")
Dim dr As OleDbDataReader = cmd10.ExecuteReader
Do While dr.Read()
DataGridView1.Rows.Add(dr("ItemNum"), dr("ItemName"), dr("ItemQty"), dr("ItemPrice"), dr("discount"), dr("subtotal"))
Loop
con.Close()
I expect that all the rows will be updated as each other, but the actual output is that each row has different qty name etc...
This code does not seem appropriate in the load event because pautotxt.Text will not have a value yet. Can you move it to a Button.Click?
I guessed that the datatype of ID is an Integer. You must first test if the the .Text property can be converted to an Integer. .TryParse does this. It returns a Boolean and fills IntID that was provided as the second parameter.
You can pass the connection string directly to the constructor of the connection. The Using...End Using blocks ensure that your database objects are closed and disposed even if there is an error. You can pass the Select statement and the connection directly to the constructor of the command.
ALWAYS use Parameters, never concatenate strings to avoid sql injection. Don't use .AddWithValue. See http://www.dbdelta.com/addwithvalue-is-evil/
and
https://blogs.msmvps.com/jcoehoorn/blog/2014/05/12/can-we-stop-using-addwithvalue-already/
and another one:
https://dba.stackexchange.com/questions/195937/addwithvalue-performance-and-plan-cache-implications
The DataAdapter will open the connection, fiil the DataTable and close the connection if it finds it closed; however if it is found open it will leave it open.
The last line binds the grid to the DataTable.
Private Sub FillGrid()
If Not Integer.TryParse(pautotxt.Text, IntID) Then
MessageBox.Show("Please enter a number")
Return
End If
dt = New DataTable()
Using con As New OleDbConnection(ConnString)
Using cmd As New OleDbCommand(Sql, con)
cmd.Parameters.Add("#ID", OleDbType.Integer).Value = IntID
Dim adap = New OleDbDataAdapter(cmd)
adap.Fill(dt)
End Using
End Using
DataGridView1.DataSource = dt
End Sub
DataTables are very clever. When bound to a DataGridView they keep track of changes and mark rows as update, insert, or delete. The DataAdapter uses this info to update the database. Once the database is updated we call .AcceptChanges on the DataTable to clear the marking on the rows.
Private Sub UpdateDatabase()
Using cn As New OleDbConnection(ConnString)
Using da As New OleDbDataAdapter(Sql, cn)
da.SelectCommand.Parameters.Add("#ID", OleDbType.Integer).Value = IntID
Using builder As New OleDbCommandBuilder(da)
da.Update(dt)
End Using
End Using
End Using
dt.AcceptChanges()
End Sub

Vb.net NO value given for one or more given parameters

Dim cmd As OleDbCommand = New OleDbCommand(Sql, con)
Dim strSql As String = "Select EmpName,Count(EmpName) from tblPO where OrderType='" &
"B2B" & "' and POExpireDate < #LogDate Group By EmpName"
Dim tstDate As DateTime = DateTime.Now
Dim dateAsString As String = tstDate.ToString("dd/MM/yy")
cmd.Parameters.AddWithValue("#LogDate", CType(dateAsString, String))
Dim dtb As New DataTable
Using dad As New OleDbDataAdapter(strSql, con)
dad.Fill(dtb)
End Using
con.Close()
I'm working in VB.NET
NO value given for one or more given parameters
error coming while filling datatable..why...how could I fix this.
pls help
Your problem is that you are passing your strSql and the connection to the data adapter but not the command which is what contains the parameter. Pass the command instead
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
'Using blocks ensure that your database objects are
'Closed And Disposed even if there Is an error.
Dim dtb As New DataTable
Using con As New OleDbConnection("Your connection string")
Dim strSql As String = "Select EmpName,Count(EmpName) from tblPO where OrderType = 'B2B' and POExpireDate < #LogDate Group By EmpName;"
Using cmd As OleDbCommand = New OleDbCommand(strSql, con)
cmd.Parameters.Add("#LogDate", OleDbType.Date).Value = DateTime.Now
'On the next line pass the command, no need to pass connection
'because it has already been passed to the constructor of the command
Using dad As New OleDbDataAdapter(cmd)
dad.Fill(dtb)
End Using
End Using
End Using
End Sub

can't connect to interbase using VB.NET

i'm pretty new in VB.NET.
i'm trying to connect INTERBASE database (local) and get an error:
I've tried many things and nothing helped.
can't figure out what am I doing wrong or missed
Imports FirebirdSql
Public Class Form1
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim query As String = "select * from EMPLOYEE"
Dim csb As FbConnectionStringBuilder
Dim cnn As New FbConnection
csb = New FbConnectionStringBuilder()
csb.DataSource = "LOCALHOST"
csb.ServerType = 0
csb.Database = "c:\db\office.gdb"
csb.UserID = "SYSDBA"
csb.Password = "masterkey"
cnn = New FbConnection(csb.ToString)
Dim da As New FirebirdSql.Data.FirebirdClient.FbDataAdapter(query, cnn)
Dim ds As New DataSet
Dim dt As New DataTable
Try
cnn.Open()
da.Fill(dt)
cnn.Close()
cnn.Dispose()
Dim ans As String
If dt.Rows.Count > 0 Then
For Each row As DataRow In dt.Rows
ans = Convert.ToString(row.Item(1))
TextBox1.Text = ans
Next
Else
TextBox1.Text = "Record Not Found"
End If
Catch ex As Exception
MessageBox.Show("Error: " & ex.Message, "Error")
End Try
End Sub
End Class
You cannot use FirebirdClient to connect to InterBase. Firebird and InterBase are not the same.
So...!!!
After digging the net I finally got it working!
Installed "Firebird_ODBC_2.0.3.154_Win32.exe" Downloaded from http://www.firebirdsql.org/en/odbc-driver/
fixed my script:
Dim query As String = "select * from EMPLOYEE"
Dim cnn As New Odbc.OdbcConnection()
Dim estring As New Odbc.OdbcConnectionStringBuilder("DRIVER=Firebird/InterBase(r) driver;UID=SYSDBA;PWD=masterkey;DBNAME=128.1.7.81:C:\office\db\office.gdb;")
cnn = New OdbcConnection(estring.ToString)
Dim da As New OdbcDataAdapter("select * from EMPLOYEE", estring.ToString)
Dim ds As New DataSet
Dim dt As New DataTable
Try
cnn.Open()
da.Fill(dt)
cnn.Close()
cnn.Dispose()
' (and so one).....
The connection established and I'm happy!
You were right about .NET OLE DB Provider for Firdbird (not working with Interbase), thank you all for the help.
I hope that this thread will help others with this problem.

How to extract data from Access db and place it into a text box using vb.net?

Hi guys I'm trying to search an employee information using SQL from MS Access, and hoping to put the fname lname and such details in their respective textbox which correspond to a specific employee's ID number. I have managed to make the SQL work but I don't know how to extract files from my sql statement and place it inside .text(text box), can you please guide me? Thanks
Here is my code so far:
(UPDATED my code) got an error message : Additional information: ExecuteReader: Connection property has not been initialized. Highlighting Reader below. How can i fix this? I'm trying to extract data and place it into the textbox? Thanks
Private Sub eNumText_SelectedIndexChanged(sender As Object, e As EventArgs) Handles eNumText.SelectedIndexChanged
Dim dbSource = "Data Source= C:\Databse\Company_db.accdb"
con.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0; Data Source= c:\Databse\Company_db.accdb"
Dim sqlQuery As String
Dim sqlCommand As New OleDbCommand
Dim sqlAdapter As New OleDbDataAdapter
Dim Table As New DataTable
Dim empNum As String
Dim empFname As String
Dim empLname As String
Dim empDept As String
Dim empStat As String
Dim empYears As String
empNum = eNumText.Text
empFname = empFnameText.Text
empLname = empLnameText.Text
empDept = DeptText.Text
empStat = StatText.Text
empYears = yearstext.Text
sqlQuery = "SELECT * FROM tbl_empinfo WHERE EmpID like empNum"
With sqlCommand
.CommandText = sqlQuery
.Connection = con
.Parameters.AddWithValue("EmpID", empNum)
With sqlAdapter
.SelectCommand = sqlCommand
.Fill(Table)
End With
With DataGridView1
.DataSource = Table
End With
End With
Dim path = "Data Source= C:\Databse\Company_db.accdb"
Dim command = "SELECT * FROM tbl_empinfo WHERE EmpID like empNum"
QueryData(path, command)
con.Close()
End Sub
Private Sub QueryData(PathDb As String, command As String)
Using connection As New System.Data.OleDb.OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & PathDb)
Using da As New System.Data.OleDb.OleDbCommand(command, connection)
connection.Open()
Dim reader = da.ExecuteReader()
If reader.Read() Then
empFnameText.Text = reader("fname")
empLnameText.Text = reader("lname")
End If
connection.Close()
End Using
End Using
End Sub
for this, you need only this classes: Connection, Command, Reader.
Other classes in the code in question, some are redundant and some are required but in complicated than a simple case presentation.
Private Sub QueryData(PathDb As String, command As String)
Using connection As New System.Data.OleDb.OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & PathDb)
Using com As New System.Data.OleDb.OleDbCommand(command, connection)
connection.Open()
Dim reader = com.ExecuteReader()
If reader.Read() Then
TextBox1.text = reader("fname")
TextBox2.text = reader("lname")
End If
connection.Close()
End Using
End Using
End Sub
call the method so:
Dim path = "C:\Databse\Company_db.accdb"
Dim command = "SELECT * FROM tbl_empinfo WHERE EmpID like empNum"
QueryData(path, command)
EDIT - Use parameters:
Private Sub QueryData(PathDb As String, command As String, id As String)
Using connection As New System.Data.OleDb.OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & PathDb)
Using com As New System.Data.OleDb.OleDbCommand(command, connection)
com.Parameters.AddWithValue("", id)
connection.Open()
Using reader = com.ExecuteReader()
If reader.Read() Then
TextBox1.Text = reader("fname")
TextBox2.Text = reader("lname")
End If
End Using
connection.Close()
End Using
End Using
End Sub
Call the method:
Dim path = "C:\Databse\Company_db.accdb"
Dim command = "SELECT * FROM tbl_empinfo WHERE EmpID = ?"
Dim empNum = "..."
QueryData(path, command, empNum)

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.