It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 10 years ago.
I'm currently working on my thesis in school and they required me to use VB2010 and MS ACCESS 2010.
what could be the easier way to connect and manipulate the DB?
is it by using MS ACCESS 2003? or MS ACCESS 2007?
I need some help because I'm new to Visual Basic 2010
Have you googled about it - insert update delete access vb.net, there are lots of reference about this.
Insert Update Delete Navigation & Searching In Access Database Using VB.NET
Create Visual Basic 2010 Project: VB-Access
Assume that, we have a database file named data.mdb
Place the data.mdb file into ..\bin\Debug\ folder
(Where the project executable file (.exe) is placed)
what could be the easier way to connect and manipulate the DB?
Use OleDBConnection class to make connection with DB
is it by using MS ACCESS 2003 or MS ACCESS 2007?
you can use any you want to use or your client will use on their machine.
it seems that you want to find some example of opereations fo the database. Here is an example of Access 2010 for your reference:
Example code snippet:
Imports System
Imports System.Data
Imports System.Data.OleDb
Public Class DBUtil
Private connectionString As String
Public Sub New()
Dim con As New OleDb.OleDbConnection
Dim dbProvider As String = "Provider=Microsoft.ace.oledb.12.0;"
Dim dbSource = "Data Source=d:\DB\Database11.accdb"
connectionString = dbProvider & dbSource
End Sub
Public Function GetCategories() As DataSet
Dim query As String = "SELECT * FROM Categories"
Dim cmd As New OleDbCommand(query)
Return FillDataSet(cmd, "Categories")
End Function
Public SubUpdateCategories(ByVal name As String)
Dim query As String = "update Categories set name = 'new2' where name = ?"
Dim cmd As New OleDbCommand(query)
cmd.Parameters.AddWithValue("Name", name)
Return FillDataSet(cmd, "Categories")
End Sub
Public Function GetItems() As DataSet
Dim query As String = "SELECT * FROM Items"
Dim cmd As New OleDbCommand(query)
Return FillDataSet(cmd, "Items")
End Function
Public Function GetItems(ByVal categoryID As Integer) As DataSet
'Create the command.
Dim query As String = "SELECT * FROM Items WHERE Category_ID=?"
Dim cmd As New OleDbCommand(query)
cmd.Parameters.AddWithValue("category_ID", categoryID)
'Fill the dataset.
Return FillDataSet(cmd, "Items")
End Function
Public Sub AddCategory(ByVal name As String)
Dim con As New OleDbConnection(connectionString)
'Create the command.
Dim insertSQL As String = "INSERT INTO Categories "
insertSQL &= "VALUES(?)"
Dim cmd As New OleDbCommand(insertSQL, con)
cmd.Parameters.AddWithValue("Name", name)
Try
con.Open()
cmd.ExecuteNonQuery()
Finally
con.Close()
End Try
End Sub
Public Sub AddItem(ByVal title As String, ByVal description As String, _
ByVal price As Decimal, ByVal categoryID As Integer)
Dim con As New OleDbConnection(connectionString)
'Create the command.
Dim insertSQL As String = "INSERT INTO Items "
insertSQL &= "(Title, Description, Price, Category_ID)"
insertSQL &= "VALUES (?, ?, ?, ?)"
Dim cmd As New OleDb.OleDbCommand(insertSQL, con)
cmd.Parameters.AddWithValue("Title", title)
cmd.Parameters.AddWithValue("Description", description)
cmd.Parameters.AddWithValue("Price", price)
cmd.Parameters.AddWithValue("CategoryID", categoryID)
Try
con.Open()
cmd.ExecuteNonQuery()
Finally
con.Close()
End Try
End Sub
Private Function FillDataSet(ByVal cmd As OleDbCommand, ByVal tableName As String) As DataSet
Dim con As New OleDb.OleDbConnection
Dim dbProvider As String = "Provider=Microsoft.ace.oledb.12.0;"
Dim dbSource = "Data Source=D:\DB\Database11.accdb"
connectionString = dbProvider & dbSource
con.ConnectionString = connectionString
cmd.Connection = con
Dim adapter As New OleDbDataAdapter(cmd)
Dim ds As New DataSet()
Try
con.Open()
adapter.Fill(ds, tableName)
Finally
con.Close()
End Try
Return ds
End Function
End Class
Refer these links:
Insert, Update, Delete & Search Values in MS Access 2003 with VB.NET 2005
INSERT, DELETE, UPDATE AND SELECT Data in MS-Access with VB 2008
How Add new record ,Update record,Delete Records using Vb.net Forms when Access as a back
A good resource start off point would be MSDN as your looking into a microsoft product
Related
So i have here my codes for fetching informations from the database using
the listview, and now i want to use the datagridview but i dont know how
to do it using the ADODB Connectionenter image description here.
If you are able to use an Odbc connection instead try this to retreive your data
Dim conn As New OleDb.OleDbConnection("path to your database")
Dim cmd As New OleDb.OleDbCommand
Dim da As New OleDb.OleDbDataAdapter
Dim sql as String
Sql = "your SQL Query"
conn.Open()
cmd.Connection = conn
cmd.CommandText = Sql
da.SelectCommand = cmd
You can try using Odbc Connection in VB.Net.
First add new Module named Connection.vb
Imports System.Data.Odbc
Module Connection
Public Con As New OdbcConnection
Public Adpt As New OdbcDataAdapter
Public Ds As New DataSet
Public Cmd As OdbcCommand
Public Read As OdbcDataReader
Public Sql As String
Public StrCon As String = "Dsn=Your DSN Name in Odbc Connector"
Public Sub Connect()
Con = New OdbcConnection(StrCon)
If Con.State <> ConnectionState.Closed Then Con.Close()
Con.Open()
End Sub
End Module
And next don't forget to add Imports System.Data.Odbc in every form you have to connect to your Odbc Connection.
Simple Code to add item on ComboBox from Database.
Call Connect()
Cmd = New OdbcCommand("SELECT * FROM `category` ", Con)
cmbKategori.Items.Clear()
cmbKategori.AutoCompleteCustomSource.Clear()
Read = Cmd.ExecuteReader()
If Read.HasRows = True Then
While Read.Read()
cmbKategori.AutoCompleteCustomSource.Add(Read("name_category"))
cmbKategori.Items.Add(Read("name_category"))
End While
End If
Private Function CreatePlayerAdapter(ByVal playerDBconnection As OleDbConnection) As OleDbDataAdapter
// Initiating instances for the function
Dim dataAdapter As OleDbDataAdapter = New OleDbDataAdapter()
Dim myCommand As OleDbCommand
Dim parameter As OleDbParameter
// establishing the string to tell where to delete record from and how to find the record i want.
// PlayerIDTextBox.Text is a text on a form that is populated from the database after selecting a list of name (this works correctly) // connection is already open and is directed to correct place
Dim sql As String = "DELETE * FROM Players WHERE ID ='" & CInt(PlayerIDTextBox.Text) & "'"
myCommand = New OleDbCommand(sql, playerDBconnection)
parameter = myCommand.Parameters.Add("ID", OleDbType.Char, 3, "ID")
parameter.SourceVersion = DataRowVersion.Original
dataAdapter.DeleteCommand = myCommand
Return dataAdapter
End Function
// i call this function after executing a button click.
//ListPlayerComboBox.Text is populated with the names and needs it a name to fill PlayerIDTextBox.Text(works correctly)
Private Sub RemovePlayerButton_Click(sender As System.Object, e As System.EventArgs) Handles RemovePlayerButton.Click
If ListPlayerComboBox.Text = " " Then
MsgBox("Please Select a Player.")
Else
Me.CreatePlayerAdapter(playerDBConnection)
End If
End Sub
// no errors occur. However, nothing is done in the database. help please?
Notes:
1)Never leave your OleDbConnection Open. Only allow it to be opened when you actually need it. This will save you from a lot of headaches later on. The reasons why can be found on following stackoverflow question.
2) There is no reason to return an OleDbDataAdapter if you don't intend on using it.
3) Use your parameters correctly : see below example2
4) Keep in mind that there are some restricted keywords in Access. Luckely for you ID isn't one. The restrictedKeywords can be found here: Keywords
I'm probably missing some further points here. Anyone should be free to add em.
Why not adjust your Function CreatePlayerAdapter to the following:
1) Without parameters
Private Sub CreatePlayerAdapter(ByVal playerDBconnection As OleDbConnection)
Dim myCommand As OleDbCommand
Dim sql As String = "DELETE * FROM Players WHERE ID =" & CInt(PlayerIDTextBox.Text)
myCommand = New OleDbCommand(sql, playerDBconnection)
playerDBconnection.Open()
myCommand.ExecuteNonQuery()
playerDBconnection.Close()
End Sub
2) With parameters
Private Sub CreatePlayerAdapter(ByVal playerDBconnection As OleDbConnection)
Dim myCommand As OleDbCommand
Dim sql As String = "DELETE * FROM Players WHERE ID = #playerId"
myCommand = New OleDbCommand(sql, playerDBconnection)
Dim param As New OleDb.OleDbParameter(#playerId", CInt(PlayerIDTextBox.Text))
myCommand.Add(param)
playerDBconnection.Open()
myCommand.ExecuteNonQuery()
playerDBconnection.Close()
End Sub
The method ExecuteNonQuery executes the query passed to the command on the specified OleDbConnection and returns the number of rows affected. More info Here
I am trying to link a VB application with a MS access database.
The only way I seem able to do this is through adding a data source. Is there a way or doing this so you use it as an external and code to the file location rather than actually uploading the database to vb?
Thanks
Imports System.Data.Oledb
Dim con As New OledbConnection("Provider=microsoft.Jet.oledb.4.0DataSource=D:\mydata.mdb;")
Dim cmd As New OledbCommand
Public Sub New()
con.Open()
cmd.Connection = con
cmd.CommandText = "SELECT * FROM table1"
End Sub
I was developing an application using oop concept.I have a class that has 2 attributes and have Get and Set methods namely WorkItemNumber and Description.
On the client side i have a list box used to populate the work items based on their description.Here's the code i wrote in the class o read items from the database.
Public Sub LoadWorkItem()
' Load the data.
' Select records.
Dim oWorkItem As WorkItem = New WorkItem()
Dim conn As New OleDbConnection
Dim data_reader As OleDbDataReader
conn = oWorkItem.GetDbConnection()
Dim cmd As New OleDbCommand("SELECT * FROM work_item ORDER BY [work item number]", conn)
data_reader = cmd.ExecuteReader()
'ListBox1.Items.Clear()
If data_reader.HasRows = True Then
Do While data_reader.Read()
WorkItemNumber = data_reader.Item("work item number")
Description = data_reader.Item("description")
Loop
End If
data_reader.Close()
data_reader = Nothing
cmd.Dispose()
cmd = Nothing
conn.Close()
conn.Dispose()
End Sub
How do i populate the listbox using the code,and if there's any improvement on the code please do tell me as well.Thank you
To poulate your ListBox, do this...
ListBox1.Item.Clear()
If data_reader.HasRows Then
Do While data_reader.Read()
WorkItemNumber = data_reader.Item("work item number")
Description = data_reader.Item("description")
ListBox1.Items.Add(New ListItem(Description, WorkItemNumber)
Loop
End If
As far as improvements, start by using a Using statement for the DB connection. In your code, if there is an exception while the database connection is open, it will never get closed. This is better...
Using conn As OleDbConnection = oWorkItem.GetDbConnection()
' Execute SQL and populate list...
End Using
The above code assures that your connection will be closed.
Then, turn on Option Strict and Option Explicit. This will force you to declare the Type for Description and WorkItemNumber and cast them as Strings when adding a ListItem. This will reduce run-time errors.
Finally, if this is anything but a small app you are doing as a learning experiment, you should read up on tiered application design. Your code is mixing UI, business logic, and data access in the same method. This is generally frowned upon.
Your "user interface" LoadWorkItem() method should ask a "core" method for a list of WorkItems.
Your core method should then ask a "data access" method for data.
The "data access" method should make the call to the database.
Happy coding.
Update: You can find excellent info about n-Tier architecture on MSDN. A good book to read once you grasp the fundamentals and have some confidence in .NET is Visual Basic .NET Business Objects.
Imports System.Data.SqlClient 'Reference The Sql Client
Public Class Form1
''Make sure to change the connection string below to your connection string this code only works for SQL DataBase. If Your connection String is wrong This will Not Work
Dim connString As String = "Data
Source=NameofYourSQLServer\SQLEXPRESS;Initial Catalog=NameOfYourDataBase;Integrated Security=True"
Dim tblDIV As DataTable
Dim daDIV As SqlDataAdapter
Dim dsDIV As New DataSet
Dim oCon As SqlConnection
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim oCon = New SqlConnection
oCon.ConnectionString = connString
dsDIV = New DataSet
' Select all Fields and order by ID or Replace * with name of Field
daDIV = New SqlDataAdapter("SELECT * FROM NameOfYourTable ORDER BY Id DESC", oCon)
'*** Define command builder to generate the necessary SQL
Dim builder As SqlCommandBuilder = New SqlCommandBuilder(daDIV)
builder.QuotePrefix = "["
builder.QuoteSuffix = "]"
Try
daDIV.FillSchema(dsDIV, SchemaType.Source, "DIV")
daDIV.Fill(dsDIV, "DIV")
tblDIV = dsDIV.Tables("DIV")
ListBox1.DataSource = tblDIV
ListBox1.DisplayMember = "NameOfTheFieldYouWanttoDisplay"
Catch ex As Exception
MsgBox("Encountered an Error;" & vbNewLine & ex.Message)
oCon.Close()
End Try
End Sub
I get an error when I am trying to connect to a Microsoft Access DB using VB.NET. I see examples all over the web. My code looks like those examples, however I am getting a build error message stating:
Type 'System.Data.OleDb.OleDbConnection' is not defined.
I have tried adding some kind of import statement for the system.data.oledb... but that does not seem to work. My code is below. It is a basic connection so I am thinking that I am missing some kind of add in, library, or setting. Any and all help would be greatly appreciated.
Public Function TestMain(ByVal args() As Object) As Object
' Connection String to MS Access DB
Dim connectStr As String = "Provider=Microsoft.ACE.OLEDB.12.0;" & _
"Data Source=C:\Users\DMalerman\keyword.accdb;" & _
"Persist Security Info=False;"
MsgBox(connectStr)
' Create connection to the db
Using connection As New System.Data.OleDb.OleDbConnection(connectStr)
' Create the SQL Query
Dim readQuery As String = "Select KeywordDriver.ScriptName from KeywordDriver " & _
"where KeywordDriver.Keyword = test"
Dim queryCommand As New System.Data.OleDb.OleDbCommand(readQuery, connection)
'Open the Connection
connection.Open()
' Query the Database
Dim dbReader As System.Data.OleDb.OleDbDataReader = queryCommand.ExecuteReader()
' Loop until there is nothing left to read
While dbReader.Read()
Dim sKeyword As String = ""
sKeyword = dbReader.GetString(0)
MsgBox(sKeyword)
End While
' Close the Reader
dbReader.Close()
End Using
Return Nothing
End Function
did you try
imports System.Data.OleDb
?
if so, did it give you an error?
Please try to modify this line:
Dim queryCommand As New System.Data.OleDb.OleDbCommand(readQuery, connection)
by putting these only:
Dim queryCommand As New System.Data.OleDb.OleDbCommand(readQuery)
queryCommand.Connection = connection
Imports System.Data
Imports System.Data.OleDb
Module Module1
Public str As String
Public con As OleDbConnection
Public cmd As OleDbCommand
Public dtreader As OleDbDataReader
Public dtadapter As OleDbDataAdapter
Public Sub openconn()
str = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=|DataDirectory|\Database2.mdb"
con = New OleDbConnection(str)
Try
con.Open()
Catch ex As Exception
MessageBox.Show("gagal koneksi")
End Try
End Sub
End Module