How to use oledbconnection in vb.net - vb.net

I am new to the vb and I want to create project where if I click this button, form 2 will show and the information from it will change depends on what room button I click. i know how to connect a database but I am so clueless on how to make it that way, please help me. Thank you everyone
Dim con As New OleDb.OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Users\arima\Documents\Consumer & rooms Database.mdb")
Yup, Stuck

You also need an OleDbCommand associated with the connection. The OleDbCommand.CommandText property is where your SQL statements go. Then you can .Open() the connection, so the command object can execute the SQL statements.
Here's the general idea:
Using con As New OleDbConnection("connection string here"), _
cmd As New OleDbCommand("SELECT * FROM MyTable WHERE MyColumn = ?", con)
cmd.Parameters.Add("?", OleDbType.VarWChar, 25).Value = "SomeValue"
con.Open()
Using rdr As OleDbDataReader = cmd.ExecuteReader()
While rdr.Read()
' Do something with each record
End While
End Using
End Using
Alternatively, you can use an OleDbDataAdapter to fill a DataTable or DataSet:
Dim dt As New DataTable
Using con As New OleDbConnection("connection string here"), _
da As New OleDbDataAdapter("SELECT * FROM MyTable WHERE MyColumn = ?", con)
da.SelectCommand.Parameters.Add("?", OleDbType.VarWChar, 25).Value = "SomeValue"
da.Fill(dt)
End Using

Related

VB.net | how can i turn an access db record in to a tabcontrol add tabpage?

I have a question, I want to add a TabPage to my TabControl from an access record? I think it's something along these lines but it didn't work:
Dim con As OleDbConnection = New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & My.Application.Info.DirectoryPath.ToString() & "\data\testing.Accdb;Persist Security Info=False;")
con.Open()
Dim constr As String = "SELECT ProductType, Discription FROM TblProductType"
Dim cmd As OleDbCommand = New OleDbCommand(constr, con)
Dim da As OleDbDataAdapter = New OleDbDataAdapter(cmd)
Dim ds As DataSet = New DataSet()
da.Fill(ds, "TblProductType")
Me.TabControl1.TabPages.Add("Discription")
con.Close()
You have to iterate over the row collection of the table:
Using cmd As New OleDbCommand("SELECT ProductType, Discription FROM TblProductType", con)
Using rdr As OleDbDataReader = cmd.ExecuteReader
While rdr.Read
TabControl1.TabPages.Add(rdr("Discription").ToString)
End While
End Using
End Using
Of course, this only gives you an empty TabPage for every record and in it's current implementation, you don't have any reference to the record anymore. That ProductType, if it's unique, should be used somewhere, too.

How to call a query from MS Access 2010 (.accdb) within VB.Net 2010?

I have this code that populates a datagridview with data from ms access:
Dim con As New OleDbConnection
Dim ds As New DataSet
Dim da As OleDb.OleDbDataAdapter
Dim Sql As String
Sql = "SELECT * FROM myTable WHERE case_no=?"
Try
con.ConnectionString = "PROVIDER=Microsoft.ACE.OLEDB.12.0;Data Source=Sample.accdb;Persist Security Info=True;Jet OLEDB:Database Password=dbadmin2010"
con.Open()
Dim cmd As OleDbCommand = New OleDbCommand(Sql, con)
da.SelectCommand = cmd
cmd.Parameters.AddWithValue("case_no", case_no)
Dim ds As DataSet = New DataSet
da.Fill(ds, "Case Info")
DataGridView1.DataSource = ds.Tables("Case Info")
Catch ex As Exception
MsgBox(ex.Message)
End Try
Now I had just finished creating a query from design view within MS Access itself, is there a way to call that query and retrieve the results to my datagridview?
Just use the query name and set the command type, for example, in addition to what you already have, you can use the following notes:
Try
con.ConnectionString = enter_connection_string_here
con.Open()
cmd.Connection = con
cmd.CommandType = CommandType.StoredProcedure
cmd.CommandText = "NameOfQuery"
da.SelectCommand = cmd
cmd.Parameters.AddWithValue("case_no", case_no)
da.Fill(ds, "Case Info")

Possible to have multiple SqlCommand?

Dim conn As New SqlConnection("Database=Clinic_Management_System;Data Source=.\SQLExpress;Integrated Security=True;AttachDBFilename=|DataDirectory|Clinic Management System.mdf")
Dim cmd As SqlCommand
Dim dr As SqlDataReader
conn.Open()
cmd = New SqlCommand("INSERT INTO record([PatientID],[Prescription],[VisitDate]) Values ('" & PatientIDTextBox.Text & "','" & txtPrescription.Text & "',GetDate()) ", conn)
cmd.ExecuteNonQuery()
For cn As Integer = 0 To DataGridView1.RowCount - 1
cmd = New SqlCommand("INSERT INTO record_item([RecordID],[ItemID],[Amount]) Values ( (SELECT MAX(RecordID) FROM record)," & DataGridView1.Rows(cn).Cells(0).Value & "," & DataGridView1.Rows(cn).Cells(2).Value & ")", conn)
cmd.ExecuteNonQuery()
Next
conn.Close()
Is this possible to run 2 SqlCommand together??
Because after executed somehow the 2nd inside the loop did not execute or insert data.
You don't have 2 SqlCommands.
You have 1 SqlCommand, called cmd, which is executed multiple times.
It is fine to do something like this, however I would have 1 SqlCommand for your INSERT INTO record, and 1 for your INSERT INTO record_item. I think this makes it much easier to understand when looking back at the code at a later date.
Either way, using a SqlCommand like this should not prevent it from executing, therefore I believe there is another issue with your scripting.
I've adapted your code so that it is split into 2 seperate SqlCommand objects, and the queries have been parameterized to prevent SQL Injection:
Dim conn As New SqlConnection("Database=Clinic_Management_System;Data Source=.\SQLExpress;Integrated Security=True;AttachDBFilename=|DataDirectory|Clinic Management System.mdf")
Dim cmdRecord As New SqlCommand("INSERT INTO record ([PatientID],[Prescription],[VisitDate]) Values (#PatientID, #Prescription, GETDATE())", conn)
cmdRecord.Parameters.Add("#PatientID", SqlDbType.Int).Value = PatientIDTextBox.Text
cmdRecord.Parameters.Add("#Prescription", SqlDbType.NVarChar).Value = txtPrescription.Text
Dim cmdRecordItem As New SqlCommand("INSERT INTO record_item([RecordID],[ItemID],[Amount]) Values ( (SELECT MAX(RecordID) FROM record),#ItemID,#AmountID)", conn)
cmdRecordItem.Parameters.Add("#ItemID", SqlDbType.Int)
cmdRecordItem.Parameters.Add("#Amount", SqlDbType.Decimal)
Dim dr As SqlDataReader
conn.Open()
cmdRecord.ExecuteNonQuery()
For cn As Integer = 0 To DataGridView1.RowCount - 1
cmdRecordItem.Parameters("#ItemID").Value = DataGridView1.Rows(cn).Cells(0).Value
cmdRecordItem.Parameters("#Amount").Value = DataGridView1.Rows(cn).Cells(2).Value
cmdRecordItem.ExecuteNonQuery()
Next
conn.Close()
One command can only be used once.
If you want to use more than one command, declare a new cmd as
Dim cmd2 as SqlCommand
In order to ensure that either all statements complete successfully or that none do, you need to wrap your commands in a transaction.
Using parameters for the commands will also make the code more understandable and safer and you should use using statements where possible.
Also, performing the Select max recordid is a very bad idea (if you have multiple users), but I'll leave that for another time:
Using conn As New SqlConnection("Database=Clinic_Management_System;Data Source=.\SQLExpress;Integrated Security=True;AttachDBFilename=|DataDirectory|Clinic Management System.mdf")
Dim cmdRecord As SqlCommand
Dim cmdRecordItem As SqlCommand
Dim oTran As SqlTransaction = Nothing
conn.Open()
Try
cmdRecord = New SqlCommand("INSERT INTO record([PatientID],[Prescription],[VisitDate]) Values (#PatientID, #Prescription, GetDate())", conn)
cmdRecord.Parameters.AddWithValue("#PatientID", PatientIDTextBox.Text)
cmdRecord.Parameters.AddWithValue("#Prescription", txtPrescription.Text)
cmdRecordItem = New SqlCommand("INSERT INTO record_item([RecordID],[ItemID],[Amount]) SELECT ISNULL(MAX(RecordID), 0), #ItemID, #Amount FROM record", conn)
cmdRecordItem.Parameters.Add("#ItemId")
cmdRecordItem.Parameters.Add("#Amount")
oTran = conn.BeginTransaction
cmdRecord.ExecuteNonQuery()
For Each oRow As DataGridViewRow In DataGridView1
cmdRecordItem.Parameters("#ItemId").Value = oRow.Cells(0).Value
cmdRecordItem.Parameters("#Amount").Value = oRow.Cells(2).Value
cmdRecordItem.ExecuteNonQuery()
Next
oTran.Commit()
Catch
If oTran IsNot Nothing Then
oTran.Rollback()
End If
Throw
Finally
conn.Close()
End Try
End Using

Retrieving rows from a MS Access Database View using Vb.Net

I've managed to get the following code...
con.ConnectionString = My.Settings.dbConnection
Dim sqlCmd As System.Data.OleDb.OleDbCommand = New System.Data.OleDb.OleDbCommand()
con.Open()
sqlCmd.Connection = con
Dim schemaTable As DataTable
schemaTable = con.GetOleDbSchemaTable(System.Data.OleDb.OleDbSchemaGuid.Views, Nothing)
To retrieve a list of Views in my Access database, but now I want to retrieve the results based on a selected View.
Is there a correct method in doing this, or do I take the SQL Statement from the DataTable returned for each row?
Suppose you have Query1 (View) in your Access database (Database1.accdb file). The following code will output each row of the query to the console (for demo purposes):
Dim con As OleDbConnection = New OleDbConnection()
con.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Database1.accdb;Persist Security Info=False;"
Dim sqlCmd As OleDbCommand = New System.Data.OleDb.OleDbCommand()
sqlCmd.CommandType = CommandType.StoredProcedure
sqlCmd.CommandText = "Query1"
sqlCmd.Connection = con
con.Open()
Dim reader As OleDbDataReader
reader = sqlCmd.ExecuteReader()
If reader.HasRows Then
While reader.Read()
Console.WriteLine(reader("Column1")) 'output specific column
End While
End If
Console.ReadLine()
Hope this helps

How to determine the id of a data in vb.net?

I'm currently working on an ms access database in vb.net.
And I need a code that can determine which data I am updating in the database. Because when I try to update the data, the previous data is being cloned and it will generate two data(the updated and the previous data), and the program will also generate a random id number for the updated data, which is not good.
Here is my code for the update button:
'update
Dim cb As New OleDb.OleDbCommandBuilder(da)
ds.Tables("GH").Rows(INC).Item(1) = TextBox13.Text
ds.Tables("GH").Rows(INC).Item(2) = TextBox14.Text
ds.Tables("GH").Rows(INC).Item(3) = TextBox15.Text
da.Update(ds, "GH")
MsgBox("Data updated")
My code for form load:
con.ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=F:\ACCESS DATABASE\search.mdb"
con.Open()
sql = "SELECT * FROM GH"
da = New OleDb.OleDbDataAdapter(sql, con)
da.Fill(ds, "GH")
con.Close()
I'm using system.data.oledb namespace
Here are my declarations:
Dim cmd As OleDbCommand
Dim cn As OleDbConnection
Dim dr As OleDbDataReader
Dim ds As New DataSet
Dim con As New OleDb.OleDbConnection
Dim da As OleDb.OleDbDataAdapter
Your question is not clear to me at all, but if you want to find the last ID of an insert, you would usually check the results of "SELECT ##IDENTITY" immediately after the record is inserted.