Reading tables using OleDBConnection - vb.net

First off, i'm new to VB and this is my first project using OleDBConnection.
ok, so i'm trying to the most simple thing using oleDbConnection (i assume). I just want to read data from a table in the Access DB and display that information to dropboxes (or anything) in my winForm.
Public Class QueManger
Dim dbConnection As OleDbConnection
Dim dbCommand As OleDbCommand
Dim dbDataAdapter As OleDbDataAdapter
Dim ConnectString As String = "Provider = Microsoft.Jet.OLEDB.4.0;" & "Data Source = \\atrts10\F:\Applications\ATRTaxCert\Development\mtaylor\TaxCert_be_test.accdb"
Dim dtMain As DataTable
Private Sub QueManger_Load(sender As Object, e As EventArgs) Handles MyBase.Load
StatusName()
End Sub
Private Sub StatusName()
Dim taxconn As OleDbConnection
Try
taxconn = New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=\\atrts10\F:\Applications\ATRTaxCert\Development\mtaylor\TaxCert_be_test.accdb")
Dim taxcmd As OleDbCommand = taxconn.CreateCommand
taxcmd.CommandText = "SELECT StatusName FROM Status ORDER BY StatusName"
Dim rdr2 As OleDbDataReader
If taxconn.State = ConnectionState.Closed Then
taxconn.Open()
End If
rdr2 = taxcmd.ExecuteReader
'boxStatus.Items.Add("All")
While rdr2.Read()
boxClient.Items.Add(rdr2.Item("StatusName"))
End While
Catch ex As Exception
Finally
taxconn.Close()
End Try
End Sub
The error comes when it tries to run the "taxconn.Open()" function.
The error says "The Microsoft Access database engine cannot open or write to the file '\atrts10\F:\Applications\ATRTaxCert\Development\mtaylor\TaxCert_be_test.accdb'. It is already opened exclusively by another user, or you need permission to view and write its data."
any thoughts?

try to close the opened table first in access if you are editing them, and try to add "#" before the string to use your path.
then try to use this connection string;
string connectionString = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + yourDataBasePath + ";Persist Security Info=False;";

Related

i am currently getting this error, System.InvalidOperationException: 'Fill: SelectCommand.Connection property has not been initialized.'

Imports System.Data
Imports System.Data.OleDb
Imports System.Data.DataTable
Public Class Form1
Private Sub btnlogin_Click(sender As Object, e As EventArgs) Handles btnlogin.Click
Dim conn As New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\Katlego\Documents\LoginDb.accdb")
Dim cmd As New OleDbCommand("select * from logintable where username1=#username1 and password1=#password1, conn")
cmd.Parameters.Add("#username1", oleDbType:=OleDbType.VarChar).Value = txtusername.Text
cmd.Parameters.Add("#password1", oleDbType:=OleDbType.VarChar).Value = txtpassword.Text
Dim adapter1 As New OleDbDataAdapter(cmd)
Using logintable As New DataTable
Dim unused = adapter1.Fill(logintable)
If logintable.Rows.Count <= 0 Then
MsgBox("error username or password")
Else
MsgBox("login sucessfull")
End If
End Using
End Sub
You need to open the connection first
conn.Open()
There's a typo when you are initializing cmd object. You include the conn object inside the connection string. So the cmd object is missing a connection object.
Dim cmd As New OleDbCommand("select * from logintable where username1=#username1 and password1=#password1, conn")
Should be:
Dim cmd As New OleDbCommand("select * from logintable where username1=#username1 and password1=#password1", conn)
It is usually a good idea to separate you user interface code (where you click buttons and show message boxes) from your database code.
Connections, Commands and DataAdapters need to be disposed so they can release their unmanaged resources. Using...End Using blocks will do this for us.
Since you only want to know if the record exits you can just get the count. You had a typo in your command text. The closing quote included the conn.
We don't need DataTable or DataAdapter. That single piece of data only requires an ExecuteScalar which returns an Object so we need the CInt.
Private Sub btnlogin_Click(sender As Object, e As EventArgs) Handles btnlogin.Click
If IsLoginValid(txtusername.Text, txtpassword.Text) Then
MsgBox("login sucessfull")
Else
MsgBox("error username or password")
End If
End Sub
Private Function IsLoginValid(uname As String, pword As String) As Boolean
Dim count As Integer
Using conn As New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\Katlego\Documents\LoginDb.accdb"),
cmd As New OleDbCommand("select Count(*) from logintable where username1=#username1 and password1=#password1;", conn)
cmd.Parameters.Add("#username1", OleDbType.VarChar).Value = uname
cmd.Parameters.Add("#password1", OleDbType.VarChar).Value = pword
conn.Open()
count = CInt(cmd.ExecuteScalar)
End Using
If count = 1 Then
Return True
End If
Return False
End Function
There is still a big problem with the code. Passwords should NEVER be stored as plain text. They need to be salted and hashed but that is beyond the scope of this question.

How to fill a ComboBox using records from an Access database

I want to retrieve the data and display in a ComboBox but it's showing blank.
This is my code:
Imports System.Data.OleDb
Public Class frmAirwaybill
Private Sub frmAirwaybill_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
Dim cm As OleDbCommand = New OleDbCommand("select acc_no from tblshipper order by acc_no")
cm.Connection = DBconnection()
Dim dr As OleDbDataReader = cm.ExecuteReader
Do While (dr.Read())
txtAccountNo.Items.Add(dr.Item("acc_no"))
Loop
dr.Close()
DBconnection.Close()
End Sub
End Class*
txtAccountNo is the ComboBox
What I want, when the form loads, is to load the accno from my database. How do I do that?
This is a screenshot showing the ComboBox with blank values:
My database connection is OK.
This is my connection on module file
Public Function DBconnection() As OleDbConnection
Dim con As New OleDb.OleDbConnection
Dim constring As String = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & Application.StartupPath & "\SmartshipG2.mdb"
con = New OleDb.OleDbConnection(constring)
con.Open()
Return con
End Function
The first thing to note is that you haven't opened the connection. This is probably the root cause.
That said, you are better binding to the .DataSource of the ComboBox using a DataTable and setting the .DisplayMember and .ValueMember properties.
I would also consider implementing Using:
Sometimes your code requires an unmanaged resource, such as a file handle, a COM wrapper, or a SQL connection. A Using block guarantees the disposal of one or more such resources when your code is finished with them. This makes them available for other code to use.
Lastly, consider giving your ComboBox a better prefix. txt is often used for TextBox controls. I use cmb whilst others may use cbx. So in this case cmbAccountNo seems a better fit.
With the changes you code would look something like this:
Dim dt As New DataTable
Using con As OleDbConnection New OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & Application.StartupPath & "\SmartshipG2.mdb"),
cmd As New OleDbCommand("SELECT [acc_no] FROM [tblshipper] ORDER BY [acc_no]", con)
con.Open()
dt.Load(cmd.ExecuteReader())
End Using
cmbAccountNo.DataSource = dt
cmbAccountNo.DisplayMember = "acc_no"
cmbAccountNo.ValueMember = "acc_no"

VB.Net SQL Connection problems

I am working on a Windows CE application programmed in VB. I am trying to add in an SQL Connection so the application will access the database and retrieve the required information. I have tried a lot of different connection strings with no luck. Can anyone point out what I am doing wrong? Or suggest a way forward as at this stage any suggestions would help. Thanks in advance
The code below is the code I am using to try and access the SQLDatabase
Public Class SQLTest
Dim sqlCMD As SqlCommand
Dim myDA As SqlDataAdapter
Dim myDataSet As DataSet
Private Sub SQLTest_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
'"Data Source=.;Integrated Security=True;AttachDbFilename=|DataDirectory|\SqlDatabase.mdf"
Dim con As SqlConnection = New SqlConnection("Data Source=192.168.1.62,1433;Initial Catalog=CASILynasFulfilment;User ID=rfgun;Password=Casiuk2012*;")
' Dim con As SqlConnection = New SqlConnection("Data Source=192.168.1.62;Integrated Security=True;AttachDbFilename=|DataDirectory|\master.mdf")
Dim cmd As String = "SELECT * FROM [Order]"
'Dim cmd As SqlCommand = New SqlCommand("SELECT * FROM [Order]")
con.Open()
sqlCMD = New SqlCommand(cmd, con)
Dim sqlReader As SqlDataReader = sqlCMD.ExecuteReader()
While sqlReader.Read()
MsgBox(sqlReader.Item(0) & " - " & sqlReader.Item(1) & " - " & sqlReader.Item(2))
End While
sqlReader.Close()
sqlCMD.Dispose()
con.Close()
'Automatically generates DeleteCommand, UpdateCommand and InsertCommand for DataAdapter object
' Dim builder As SqlCommandBuilder = New SqlCommandBuilder(myDA)
' myDataSet = New DataSet()
' myDA.Fill(myDataSet, "MyTable")
' DataGrid1.DataSource = myDataSet.Tables("MyTable").DefaultView
' con.Close()
' con = Nothing
End Sub
The image below is the error I am getting.
Are You writing your connection string manually?
if yes, then don't do that
just open youre server explorer
select your server name (which is your machine name)
select your db file
and test connection by clcik on 'test connection button'
if success, then just copy the connection string by righr click on your db file
and paste it where you required it
I figured out the problem. In the Configuration Manager Named Pipes were not enabled so it would not allow a connection to the database.

OleDbException was unhandled, syntax error in WHERE clause?

Having trouble with a persistent error. My form allows the user to see a list of elements in a particular group. The input for group number is a combobox called groupbox and the output is a combobox called ElementResults. I am getting the error on the line: GroupSearch.ExecuteNonQuery()
Imports System.Data.OleDb
Public Class ElementsSearch
Public Shared connectionString As String = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Documents and Settings\A\My Documents\Visual Studio 2010\Projects\A2\Element.accdb;Persist Security Info=False;"
Public Shared ElementsTable
Private Sub Button2_Click(sender As System.Object, e As System.EventArgs) Handles Button2.Click
Dim Search As New OleDbConnection(connectionString)
Search.Open()
Dim SearchCriteria As String
SearchCriteria = Groupbox.Text
Dim query As String = "SELECT * From ElementsTable WHERE Group='" & SearchCriteria & "'"
Dim GroupSearch As New OleDbCommand(query, Search)
GroupSearch.ExecuteNonQuery()
Dim reader As OleDbDataReader = GroupSearch.ExecuteReader()
ElementResults.Text = Convert.ToString(reader("Name"))
End Sub
End Class
You define the field group which is a reserved keyword.
Try [group] instead like in this sample:
SELECT * From ElementsTable WHERE [Group]='aaa'
To avoid all the errors you're getting, consider changing your code to something like this:
Using connection As New OleDbConnection(connectionString)
connection.Open()
Using command As New OleDbCommand("SELECT * From ElementsTable WHERE [Group]=#Group", connection)
command.Parameters.AddWithValue("#Group", SearchCriteria)
Using reader As OleDbDataReader = command.ExecuteReader()
Do While reader.Read()
ElementResults.Text = reader.GetString("Name")
Loop
End Using
End Using
End Using

ExecuteReader CommandText property has not been properly initialized

First of all sorry if some of the code isn't right. I'm still new to using sql on vb.net
I have the following code:
Imports MySql.Data.MySqlClient
Imports System.Data.SqlClient
Public Class Form1
Private Sub btnLoad_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnLoad.Click
Dim objConn As MySqlConnection
Dim objDataset As New DataSet
Dim objDataAdapter As MySqlDataAdapter
Dim myCommand As MySqlCommand
Dim sqlConn As String
objConn = New MySqlConnection("server=localhost;userid=root;database=attendance_system")
myCommand = objConn.CreateCommand
objConn.Open()
Dim objReader As MySqlDataReader = myCommand.ExecuteReader
sqlConn = "SELECT student_name FROM profile"
objDataAdapter = New MySqlDataAdapter(sqlConn, objConn)
objDataAdapter.Fill(objDataset, "profile")
MsgBox("The Connection is Now 'OPEN'")
objReader.Read()
TextBox1.Text = objReader("student_name")
objReader.Close()
objConn.Close()
End Sub
End Class
I am using MySQL connector via vb.net in phpmyadmin and have set a database with records.
The connection string is working, but my problem is when I try to click the button to load the data in the textbox, I keep getting:
The CommandText property has not been properly initialized."
The error is on this line:
"Dim objReader As MySqlDataReader = myCommand.ExecuteReader"
I've tried a lot of fixes that I've found on this site and the others as well.
This is the problem:
Dim objReader As MySqlDataReader = myCommand.ExecuteReader
sqlConn = "SELECT student_name FROM profile"
You're declared the SQL after you've tried executing the query (and even then you don't set it as the SQL for the command). How would you expect that to work? Additionally, sqlConn is a very strange name for a variable declaring the SQL - I'd expect it to be a connection.
It looks like you're trying to mix too very different ways of fetching data:
Reading directly from the reader
Filling a DataSet with a data adapter
You shouldn't be mixing them like that. Work out which you actually want to do, take out all the code related to the other style, and then make sure you're doing everything in a sensible order.
From MySqlCommand Class and the example given as
Public Sub ReadMyData(myConnString As String)
Dim mySelectQuery As String = "SELECT * FROM Test.Dept"
Dim myConnection As New MySqlConnection(myConnString)
Dim myCommand As New MySqlCommand(mySelectQuery, myConnection)
myConnection.Open()
Dim myReader As MySqlDataReader = myCommand.ExecuteReader()
Try
While myReader.Read()
Console.WriteLine(myReader.GetInt32(0).ToString() + ", " _
+ myReader.GetString(1))
End While
Finally
' always call Close when done reading.
myReader.Close()
' always call Close when done with connection.
myConnection.Close()
End Try
End Sub
Your command object is missing the select statement.