system.data.sqlclientexception:incorrect syntax near '#p2' - sql-server

I am trying to insert, update the data on Grid in VB.net windows application which has to update the data in database. I am not able to achieve this functionality using new schema name(Customer) but when I try to create table with schema "dbo" I am able insert, update the data on grid and able to see the data in SQL Server as well.
Please help me what I need to change in code perform insert and update options.
code:
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim test1 As String
test1 = "Select * from Customer.CustomerID"
connection = New OleDbConnection
connection.ConnectionString = "Provider=MSOLEDBSQL.1;Integrated Security=SSPI;Initial Catalog=prod;Data Source=IN-TESTVM;Use Procedure for Prepare=1;Auto Translate=True;Packet Size=4096;Workstation ID=IN-TESTVM;Use Encryption for Data=False;Tag with column collation when possible=False;MARS Connection=False;DataTypeCompatibility=0;Trust Server Certificate=False;Application Intent=READWRITE;MultisubnetFailover=False;Use FMTONLY=False;"
connection.Open()
myDA = New OleDbDataAdapter(test1, connection)
dsDataGrid = New DataSet
myDA.Fill(dsDataGrid)
grid.DataSource = dsDataGrid.Tables(0)
bindsrc2.DataSource = dsDataGrid
connection.Close()
End Sub
Button click event code is like as below
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
app = New OleDbCommandBuilder(myDA)
bindsrc2.EndEdit()
myDA.Update(bindsrc2.DataSource) 'Hitting the error while updating the data at this line
End Sub
I am able to load the data into grid using the schema name other than dbo as well.
myDA.Fill(dsDataGrid)
grid.DataSource = dsDataGrid.Tables(0)
bindsrc2.DataSource = dsDataGrid
Error message after clicking save button

Try setting the QuotePrefix and QuoteSuffix of your command builder to "[" and "]" respectively. As you are using a wildcard in your query, the command builder will not escape column names automatically and that means that keywords or spaces or other special characters will cause syntax errors.
Note that there are two alternatives. One is to not use a command builder at all and create your own action commands. In that case, you write the SQL so you escape the column names that need it. The other is to not use a wildcard in the query, in which case you will escape the column names that need it and the command builder will follow suit.

Related

SQL Server database population pre-existing Data Table and fields (FORM). NO database file

Here is my general understanding of database from what I read so far: Save / Update / Delete to pre-existing file made that binds to form thru SQL.
Here is what I am trying to do - I have a pre-made Data Table in Form with all columns defined. Once app is closed or certain functions ran, I need that data to be saved / updated in SQL (on local). Once app is open I need all that data to be preserved.
So far I have NOT found a single solution to it anywhere most refer to binding to an existing file. When I worked with Excel data transfer cells had to be defined and referenced in form for population.
My assumption is when a database from VB.NET is used, table with values can be created automatically saved/loaded/updated. However this is only my assumption since I never worked with SQL before. I am not sure if I need to manage an actual database file I created with all the values and then bind them to data table. For example DataTable cell XX to database column XX.
Here is what I done so far I have created database and added to my project. I tried few codes and I keep getting Dataset Empty even though there is Data in Table I tried to use DataTable as well but so far nothing has worked.
Please suggest on what I am doing wrong also additional information regards to databases will be great. As per previous I do know how binding works when actual file exist. But creating and managing is confusing to me since I keep thinking there should be a binding file.
Dim connetionString As String
Dim sqlCnn As SqlConnection
Dim sqlCmd As SqlCommand
Dim adapter As New SqlDataAdapter
Dim ds As New DataSet
Dim sql As String
connetionString = "Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\Data_Ant.mdf;Integrated Security=True;Connect Timeout=30"
sql = "SELECT BN FROM DataTable" ' BN is my column name and DataTable is the name of my Table where data gets populated. This is also confusing to me How does it know which value is what? Is there are space/word/characters requirements?
' adapter.TableMappings.Add("DataTable", sql)
If ds.Tables.Count > 0 Then
sqlCnn = New SqlConnection(connetionString)
Try
sqlCnn.Open()
sqlCmd = New SqlCommand(sql, sqlCnn)
adapter.SelectCommand = sqlCmd
adapter.Update(ds)
adapter.Dispose()
sqlCmd.Dispose()
sqlCnn.Close()
Catch ex As Exception
MsgBox("Can not open connection !" & vbCrLf & Err.Description)
End Try
ElseIf ds.Tables.Count = 0 Then
MsgBox("Empty data")
End If
End Sub
Code I use to Create /Save Database. As per previous all columns/formats are pre-made, loaded.
Dim connetionString As String
Dim sqlCnn As SqlConnection
Dim sqlCmd As SqlCommand
Dim adapter As New SqlDataAdapter
Dim ds As New DataSet
Dim sql As String
connetionString = "Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\Data_Ant.mdf;Integrated Security=True;Connect Timeout=30"
sql = "Select BN FROM DataTable"
adapter.TableMappings.Add("BN", sql)
If DataTable.RowCount > 0 Then
sqlCnn = New SqlConnection(connetionString)
Try
sqlCnn.Open()
sqlCmd = New SqlCommand(sql, sqlCnn)
adapter.SelectCommand = sqlCmd
adapter.Update(ds, "BN")
adapter.Dispose()
sqlCmd.Dispose()
sqlCnn.Close()
Catch ex As Exception
MsgBox("Can not open connection !" & vbCrLf & Err.Description)
End Try
ElseIf DataTable.RowCount = 0 Then
MsgBox("Empty data")
End If
End Sub
Please see more info below:
Data Table columns/format are structured for visual representation.
When User start the App Database can be empty/Can contain Values.
When users Runs certain function Closes App values are save and only values.
If I would you an MS Access I would structure same table/values and cross reference it with form values. Form Values come from outside source and Format/Qty is always known.
Hope this helps to have a cleaner look at my issue. Perhaps SQL is not a right choice for me? Does SQL needs to be build before value manipulation.
UPDATE: I Got rid of the Invalid Object error. Table had to be created 1st as I originally thought. However, My DataSet always comes up as EMPTY when I try to save... Cells do contain BN data as" 1,2, ....) Even if I to remove "If" logic Save and Load table comes out as empty. Something does load because when I try to ADD BN it tells me binding bla bla bla(different issue)
CODE:
Private Sub SaveData()
Dim connetionString As String = "Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\Data_Ant.mdf;Integrated Security=True;Connect Timeout=30"
Dim sql As String = "SELECT BN FROM DataTable_d"
Dim sqlCnn As SqlConnection
Dim sqlCmd As SqlCommand
Dim adapter As New SqlDataAdapter
Dim ds As New DataSet()
adapter.TableMappings.Add("BN", sql)
If ds.Tables.Count > 0 Then
sqlCnn = New SqlConnection(connetionString)
Try
sqlCnn.Open()
sqlCmd = New SqlCommand(sql, sqlCnn)
adapter.SelectCommand = sqlCmd
adapter.Update(ds, "BN")
adapter.Dispose()
sqlCmd.Dispose()
sqlCnn.Close()
Catch ex As Exception
MsgBox("Can not open connection !" & vbCrLf & Err.Description)
End Try
ElseIf ds.Tables.Count = 0 Then
MsgBox("Empty data")
End If
End Sub
UPDATE: I got all the things working but I can't save multiple rows..... Could really use some help
In your SQL query remove WHERE DataTable ='. This statement is looking for a column name DataTable which I assume does not exist. The WHERE clause is used to help filter your query. You only use WHERE on column names in your table.
For instance:
SELECT BN FROM DataTable
will return all values from the BN column from DataTable.
Note that if you have multiple columns, the above query will still only return values from BN.
SELECT * FROM DataTable
will return every value in DataTable.
A helpful site to look at documentation for SQL is w3schools.
Let's start with just displaying some data. Add a DataGridView to a Form. You can call LoadData() from a button. I am not very sure of you connection string but give it a try.
Private dt As DataTable
Private sql As String = "Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\Data_Ant.mdf;Integrated Security=True;Connect Timeout=30"
Private Sub LoadData()
'***EDIT*** Add instantiation line
dt = New DataTable()
'The Using...End Using blocks will close and dispose your database objects
'even if there is an error
Using cn As New SqlConnection(sql)
'You can pass the command text and the connection directly to the constructor
'In the select statement use the actual names of the field and table as they appear in the database.
Using cmd As New SqlCommand("Select BN From [Insert the name of the table in the database]", cn)
cn.Open()
dt.Load(cmd.ExecuteReader)
End Using
End Using
DataGridView1.DataSource = dt
End Sub
This is the simplest way I can think of to display data. We will proceed with changing the data once this works. If you get an error on cn.Open() We will have to work on the connection string.
****EDIT****
Private Sub TestConnection()
Dim sql As String = "Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\Data_Ant.mdf;Integrated Security=True;Connect Timeout=30"
Using cn As New SqlConnection(sql)
cn.Open()
End Using
End Sub

VB.Net forms application database table update

I am attempting to make a small application allowing users to read the content of a table describing the inventory of a warehouse, search depending on 2 rows indicating which warehouse the item resides in and by it's assigned barcode which i already managed to get to work by using a binding source, and a datagrid view, updating the view trough a query taking the barcode and location as strings from two boxes.
The second part i would need for this application to suit my basic objective would be to have a way to add new lines and store them into the original table on the database so users could add the new items independently from the warehouses directly.
So far i have encountered 2 issues: i need a primary key that would represent a sequential ID but i do not know how to produce a sequentially incrementing ID, i manage to get the first addition ID by using a top 1 order by desc query combination but the data does not get updated after adding the new line, producing an error since it tries to add another line with the same value for the primary key.
The second issue i am encountering is: the gridview gets altered accordingly to the data i input in the textboxes i set up to gather the various values for the table but the table on the database itself is not showing any change, keeping only the test data i inputted at it's creation.
Public Class AddItems
Private Sub AddItems_Load(sender As Object, e As EventArgs) Handles MyBase.Load
'TODO: This line of code loads data into the 'MagazzinoDataSet.LastUsedID' table. You can move, or remove it, as needed.
Me.LastUsedIDTableAdapter.LastUsedID(Me.MagazzinoDataSet.LastUsedID)
'TODO: This line of code loads data into the 'MagazzinoDataSet.Stock' table. You can move, or remove it, as needed.
Me.StockTableAdapter.Fill(Me.MagazzinoDataSet.Stock)
'TODO: This line of code loads data into the 'MagazzinoDataSet.AddWarehouseList' table. You can move, or remove it, as needed.
Me.AddWarehouseListTableAdapter.AddWarehouseList(Me.MagazzinoDataSet.AddWarehouseList)
'TODO: This line of code loads data into the 'MagazzinoDataSet.WarehouseList' table. You can move, or remove it, as needed.
Me.WarehouseListTableAdapter.Fill(Me.MagazzinoDataSet.WarehouseList)
'TODO: This line of code loads data into the 'MagazzinoDataSet.Stock' table. You can move, or remove it, as needed.
Me.StockTableAdapter.Fill(Me.MagazzinoDataSet.Stock)
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim R As DataRow = MagazzinoDataSet.Tables("Stock").NewRow()
R("Supplier") = Supplier.Text
R("Producer_code") = ProducerCode.Text
R("Barcode") = Barcode.Text
R("Comp_name") = ComponentName.Text
R("Warehouse") = Warehouse.Text
R("Internal_Code") = InternalCode.Text
R("Description_IT") = ITDescr.Text
R("Description_EN") = ENDescr.Text
'R("ID") = NextID.SelectedValue <- this would be an hidden uneditable multibox containing the product of the query finding the next value to be inserted in the table (basically last ID + 1, nothing fancy)"ID" would be the primary key of this table
R("Quantity") = "0"
MagazzinoDataSet.Tables("Stock").Rows.Add(R)
DataGridView1.DataSource = MagazzinoDataSet.Stock
End Sub
End Class
To sum it up:
How would i go about updating the database table to include the new line?
Is there a smart way to find the last value, incrementing it by 1 to have the next value and updating it when inserting a new line, so as to not end up with 2 lines with the same value for primary key, generating an error?
To set an incremental ID in the Db, assuming you have access to SQL Server Management Studio, in Design of the table, for the ID column, in Column Properties, scroll down to Identity Specification and set (is Identity) to Yes.
To add a new row, I use this code:
Using NotesDS As New DataSet
Using NotesDA As New SqlDataAdapter With {.SelectCommand = New SqlCommand With {.Connection = SQLDBConnection, .CommandText = "SELECT * FROM Notes WHERE ID = " & ID}}
NotesDA.Fill(NotesDS, "Notes")
Using NotesDV As New DataView(NotesDS.Tables("Notes"))
Using NoteBuilder As New SqlCommandBuilder(NotesDA) With {.QuotePrefix = "[", .QuoteSuffix = "]"}
If NotesDV.Count = 0 Then
Dim NoteDRV As DataRowView = NotesDV.AddNew
NoteDRV.Item("UserName") = UserName
NoteDRV.Item("Note") = Note
NoteDRV.Item("NoteDate") = NoteDate
NoteDRV.Item("CompanyCode") = CompanyCode
NoteDRV.EndEdit()
NotesDA.UpdateCommand = NoteBuilder.GetUpdateCommand
NotesDA.Update(NotesDS, "Notes")
End If
End Using
End Using
End Using
End Using
Obviously, amend to make appropriate for your table and column names.
If you need to retrieve the ID for display, you can add a handler to the Update like:
Public Sub GenericOnRowUpdated(sender As Object, e As System.Data.SqlClient.SqlRowUpdatedEventArgs)
Dim newID As Integer = 0
Dim idCMD As SqlClient.SqlCommand = New SqlClient.SqlCommand("SELECT ##IDENTITY", SQLDBConnection)
If e.StatementType = StatementType.Insert Then
newID = CInt(idCMD.ExecuteScalar())
e.Row("ID") = newID
End If
End Sub
and use like:
AddHandler NotesDA.RowUpdated, New SqlRowUpdatedEventHandler(AddressOf GenericOnRowUpdated)
NotesDA.Update(NotesDS, "Notes")
NewID = NoteDRV.Item("ID")
EDIT
First Example amended and explained below:
'Declare you connection to the SQL dB. Connection String looks like "Data Source=192.168.71.10\dBName; Initial Catalog=dBName; User ID=USER; Password='PASSWORD!';MultipleActiveResultSets=true" - You may well already have an open connection, and can use that instead. Not sure what your
StockBindingSource is...
Dim oConn As New SqlConnection("CONNECTION STRING")
'Open the connection
oConn.Open()
'Declare Your DataAdapter and initialise using your connection
Dim DA As New SqlDataAdapter With {.SelectCommand = New SqlCommand With {.Connection = oConn, .CommandText = "SELECT * FROM Stock WHERE ID=0"}}
'Declare you DataSet
Dim DS As New DataSet
'Fill Your DataSet with the Stock table from your DataAdapter
DA.Fill(DS, "Stock")
'Declare a DataView for easy use (really the same as using DS.Tables("Stock").DefaultView)
Dim DV As New DataView(DS.Tables("Stock"))
'Declare a CommandBuilder and initialise with your DataAdapter. This will now watch for changes made to your data and build the appropriate SQL UPDATE/INSERT/DELETE command. the "[" and "]" are in case any column names use reserved words
Dim Builder As New SqlCommandBuilder(DA) With {.QuotePrefix = "[", .QuoteSuffix = "]"}
'Decalre a DataRowView for data population, based on your DataView table structure
Dim R As DataRowView = DV.AddNew()
'Populate the fileds with your Form data
R("Supplier") = Supplier.Text
R("Producer_code") = ProducerCode.Text
R("Barcode") = Barcode.Text
R("Comp_name") = ComponentName.Text
R("Warehouse") = Warehouse.Text
R("Internal_Code") = InternalCode.Text
R("Description_IT") = ITDescr.Text
R("Description_EN") = ENDescr.Text
R("Quantity") = "0"
'Notify that the edit has finished
R.EndEdit()
'Get the SQL command from the CommandBuilder
DA.UpdateCommand = Builder.GetUpdateCommand()
'Execute the update (in this case it will be an INSERT)
DA.Update(DS, "Stock")

Change Crystal Reports db ip address in vb.net

I am currently using VB.net for getting the reports in need with Crystal Reports, My access to the SQL database server is using windows authentication , and what i need to do is to be able to change the IP address of the database source , as i am accessing a test server now , and the code will go somewhere else for work.
What i've found:
this is the only way to change the database source
CrReport.SetDatabaseLogon("user", "password", "server", "RJCards")
but then again i am using windows authentication.
P.S: when i am changing the datasource on the report it self its working great, but since we moving the application to another place, it needs to be set manually like to be retrived from a variable or something.
here is a look over my code
Private Sub GetDuplicatedFF()
Dim CrReport As New DuplicatedFF
Dim CrExportOptions As ExportOptions
CrExportOptions = CrReport.ExportOptions
Try
CrReport.SetDatabaseLogon("user", "password", "server", "RJCards")
CrReport.ExportToDisk(ExportFormatType.Excel, My.Settings.defaultDir & "\DuplicatedFF_" & Format(Now.Date, "yyyyMMdd") & ".xls")
'My.Settings.defaultDir & "\DuplicatedFF_" & Format(Now.Date, "yyyyMMdd") & ".xls"
MsgBox("Done Exporting your file")
Catch err As Exception
MessageBox.Show(err.Message)
End Try
End Sub
When you use windows authentication or credentials to access a database through Crystal Reports, that means that the data retrieval SQL statements will be included inside the rpt file. This doesn't give you too much flexibility in scenarios where you need to make changes to IP addresses, database names, etc.
There is a different approach of providing data to the report with the use of a DataSet as a source. You simply add the necessary DataTables with the necessary columns to a DataSet, fill it with data and provide it to the report. So the rpt file won't include any
embedded information (such as SQL statements).
In order to convert an existing report file to use the aforementioned approach, you can use the following steps:
Create an xsd file in your application (Add New Item... → Data → DataSet)
Edit the DataSet and add the necessary DataTable(s) (Right click → Add → DataTable)
Edit the DataTable(s) and add the necessary column(s) (Right click on DataTable → Add → Column)
Edit each column and set its properties such as DataType etc (Left click on column → Change property inside property window)
Now you need to edit the report file and change the Datasource location (Double click on the report → left click on Database Fields in Field Explorer → Set Datasource Location...)
As a Datasource replacement choose ADO.NET (XML) and double click on Make New Connection. Choose the filepath of the xsd file (DataSet) and press finish.
Each DataTable must be paired with an existing Table inside "Current Data source:" by selecting the pair and pressing the Update button.
Now the report file will just have the necessary placeholders (columns) without any database connection or SQL statements. To load data to the report, use the code below (changed according to your needs).
Imports System.Data.SqlClient
Public Class Form1
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
'Windows Authentication Connection String'
Dim ConnString As String = "Server=MyServer;Database=MyDb;Trusted_Connection=Yes;"
'The SQL statement to retrieve data'
Dim SqlStatement As String =
<SQL>
SELECT
[column1]
,[column2]
,[column3]
FROM [MyDb].[dbo].[MyTable]
</SQL>
'A new instance to the DataSet that we created'
Dim MyDataSet As New DataSet2
'A new instance to the report file'
Dim MyReport As New CrystalReport1
'A new instance to the SQL adapter'
Dim SqlAdapter As New SqlDataAdapter(SqlStatement, ConnString)
'Fills the DataTable with data retrieved from the database'
SqlAdapter.Fill(MyDataSet.Tables("TestTable1"))
'Sets the DataSet as the report source'
MyReport.SetDataSource(MyDataSet)
'Previews the report'
CrystalReportViewer1.ReportSource = MyReport
End Sub
End Class

Creating a SQL Server database for the first time at run time

I want to create a SQL Server database at runtime in my vb.net project. I know how to actually code the database but I am wondering where should I actually put the code? Should I be putting the code in the start up form or should it go into a class on it's own? Also, this project will be going on more than one pc at a particular site, so I only want the database to be created the first time the project is activated and then just be able query the database on different pcs after that. How do I do this? All help on this matter would be greatly appreciated.
EDIT:
Ok, so I should have been clearer on this. The project is going to be on 2 different pcs, it is for visitors entering a business. The pcs will be in reception and security. I need both pcs to access the same database with the same details in it. I don't want to have two different databases where details have to be put in twice. For example, if I enter at reception today and then go through security tomorrow, then all I should have to enter in security is why I'm entering the business again, I shouldn't have to put my details in a second time. How do I go about this? As I already said, I know how to code the database, but I want to know how to do what I stated in my question.
Thanks in advance for all help given.
If you add the code in module or in form load then it will execute all the time when the form loads. it is wasting of time to check whether the database exist or not in each run. So it is better to place a button with text "Create database" for this purpose(or menu item). it's click event will load the database. the following code can be used to create the database dynamically on button click
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
'creating and initializing the connection string
Dim myConnectionString As SqlConnection = New SqlConnection("Data Source=(local)\SQLEXPRESS;Initial Catalog=master;Integrated Security=True;Pooling=False")
'since we need to create a new database set the Initial Catalog as Master
'Which means we are creating database under master DB
Dim myCommand As String //to store the sql command to be executed
myCommand = "CREATE database my_db" //the command that creates new database
Dim cmd As SqlCommand = New SqlCommand(myCommand, myConnectionString) // creating command for execution
Try
cmd.Connection.Open() //open a connection with cmd
cmd.ExecuteNonQuery() //Execute the query
cmd.Connection.Close() //Close the connection
Catch
MsgBox(" Already installed database", MsgBoxStyle.Critical, " MaS InfoTech- Warning")
End Try
'Creating table to the dynamicaly created database
Try
Dim cn As SqlConnection = New SqlConnection("Data Source=(local)\SQLEXPRESS;Initial Catalog=my_db;Integrated Security=True;Pooling=False")
'here the connection string is initialized with Initial Catalog as my_db
Dim sql As String //sql query string
sql = "CREATE TABLE customer(cus_name varchar(50) NULL,address varchar(50) NULL,mobno numeric(18, 0) NULL,tin varchar(50) NULL,kg varchar(50) NULL)"
cmd = New SqlCommand(sql, cn) // create command with connection and query string
cmd.Connection.Open()
cmd.ExecuteNonQuery()
cmd.Connection.Close()
Catch
MsgBox(" Already existing table", MsgBoxStyle.Critical, " MaS InfoTech- Warning")
End Try
End Sub

Using Object to execute SQL statements in Visual Studio

I apologize if my question is simple, but I have done a lot of looking on the Internet and I am having trouble finding a solution.
I have a database connected to Visual Studio where I used the "Connect to Database..." wizard to establish the connection. In the Server Explorer in Visual Studio, I see I have a Data Connection called "newreptDBtest.accdb", and a Server named Mandrew.
Basically I would like to execute SQL statements on this database when clicking a button. So I have a button on a form, and it has the following code:
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim sqlconn As New SqlConnection
sqlconn.ConnectionString = "server=Mandrew;Initial Catalog=newreptDBtest.accdb"
Try
sqlconn.Open()
Catch ex As Exception
MessageBox.Show("Error on connection")
End Try
If sqlconn.State = 1 Then
MessageBox.Show("Success!")
End If
End Sub
In General Declarations, I have:
Imports System.Data.SqlClient
Perhaps because it's not a SQL database? I'm not sure. Either way, I have not been able to achieve the "Success!" from the MessageBox. Once I've gotten that, I'm sure I can figure out how to create SQL statements to return certain rows or single pieces of information.
In the newreptDBtest, the table I'd like to be executing queries on is called newrept, and the connection string to the database is:
"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\Andrew\Documents\newreptDBtest.accdb"
tl;dr:
How do I use an object (such as a button) to execute SQL queries on a table inside a database already connected to my project?
Thanks in advance
The classes that you need to use for accessing an MS Access database file are in the System.Data.OleDb namespace. Try this:
Dim ConnString As String = "server=Mandrew;Initial Catalog=newreptDBtest.accdb"
Dim SqlString As String = "put your query here, e.g. Select * From Contacts"
Using conn As New OleDbConnection(ConnString)
Using cmd As New OleDbCommand(SqlString, conn)
cmd.CommandType = CommandType.Text
conn.Open()
Using reader As OleDbDataReader = cmd.ExecuteReader()
While reader.Read()
'access the data using the reader, e.g. reader("ColumnName")
End While
End Using
End Using
End Using
Taken from here
Obviously, you will need to modify it to fit your query but this hightlights the fact that you need to use OleDbConnection to connect to an MS Access file.

Resources