Cannot open Access Database - vb.net

I am writing a connection string to access an Access database which is password protected but it could not open my database and it pass an exception
i.e "Cannot open database ''. It may not be a database that your application recognizes, or the file may be corrupt."
Please resolve this issue I search a lot but the problem still persists.
Here is my Code::
Public Shared DBPath As String = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & Environment.CurrentDirectory & "\AFData.accdb;Jet OLEDB:Database Password=Maint#4321;"
Public Shared Function chkdbStatus(ByRef errMessage As String) As Boolean
Dim mydbstatus As String = False
Using con As New OleDbConnection(DBPath)
Try
con.Open()
If con.State = ConnectionState.Open Then
errMessage = Nothing
mydbstatus = True
End If
Catch ex As Exception
errMessage = ex.Message
Return mydbstatus
Throw ex
Finally
con.Close()
End Try
End Using
Return mydbstatus
End Function

Related

Having the ExecuteNonQuery : connection property has not been initialized

I'm trying to delete an entry from my database. But when the ExecuteNonQuery has to do it's job it can't find the enabled connection and give me this error :
System.InvalidOperationException :'ExecuteNonQuery : connection property has not been initialized'
Here is what I did :
Dim delete As New OleDbCommand
Dim da As OleDbDataAdapter
Dim ds As DataSet
Dim dt As DataTable
initConnectionDtb(pathDtb)
openConnection()
If TextBox2.Text <> "" Then
delete.CommandText = "delete FROM USERS WHERE NAME = '" & TextBox2.Text & "'"
delete.CommandType = CommandType.Text
delete.ExecuteNonQuery()
MsgBox("USER HAS BEEN DELETED")
Else
MsgBox("ERROR")
End If
I could check if it was properly connected to the Database thanks to connectionName.State
I also enterily rewrote the connetion to the database in the function but ExecuteNonQuery still couldn't connect even though the connection was opened
I saw that i'm not the only one on this website but none of the previous answers have helped me.
#Filburt pointed out, how are you assigning your connection to your command object. Here is an example :
Using connection As OleDbConnection = New OleDbConnection(connectionString)
connection.Open()
Dim command As OleDbCommand = New OleDbCommand(queryString, connection)
command.ExecuteNonQuery()
End Using
In your code, you need to assign the connection object to your command object. We can't see what code you have in initConnectionDtb(pathDtb) or openConnection()
To adapt this to your code:
delete.Connection = <<your connection object here>>
delete.CommandText = "delete FROM USERS WHERE NAME = '" & TextBox2.Text & "'"
delete.CommandType = CommandType.Text
delete.ExecuteNonQuery()
Another note: look into parameterizing your query strings instead of hand stringing the values. This will prevent issues with TextBox2.Text having a value like O'Toole which will cause a syntax error as well as SQL Injection.
Here's what i used to initialize my connection :
Public Function initConnectionDtb(ByVal path As String) As Boolean
initConnectionDtb = True
Connection = New OleDbConnection
Try
Connection.ConnectionString = "provider=microsoft.jet.oledb.4.0;" & "data source= " & path & ";"
Catch ex As Exception
Return False
End Try
End Function
Public Function openConnection() As Boolean
openConnection = True
Try
Connection.Open()
MsgBox(Connection.State) 'to test if my connection really openned in my previous post
Catch ex As Exception
MsgBox(ex.Message)
Return False
End Try
End Function
Public Sub closeConnection()
If Not IsNothing(Connection) Then
If Connection.State = ConnectionState.Open Then
Connection.Close()
End If
MsgBox(Connection.State)
Connection.Dispose()
Connection = Nothing
End If
End Sub
So far it worked for everything i tried (adding someone to the database for exemple)

SQLite in vb 2010

I have, for over a month, tried in vain to resolve this. I am using SQLite and trying to write a simple check to see if i can connect to the database. I found some code here that was supposed to do just that.
Public Function ConnExist(strDB) As Boolean
Dim SQLconnect As New SQLite.SQLiteConnection()
Try
Using Query As New SQLiteCommand()
SQLconnect.ConnectionString = "DataSource=" & strDB & ";Version=3;New=False;Compress=True;"
SQLconnect.Open()
With Query
.Connection = SQLconnect
.CommandText = "SELECT * FROM tbltest"
End With
Query.ExecuteNonQuery()
SQLconnect.Close()
End Using
'SQLconnect.ConnectionString = "Data Source=" & strDB & ";Version=3;New=False"
'SQLconnect.Open()
'SQLconnect.Close()
Catch ex As Exception
MsgBox(ex.Message)
'Return False
End Try
Return True
End Function
I know the database is at the location specified. On the SQLconnect.Open() part it errors out and tells me datasource cannot be empty. I opened the database using DB Browser and it is not corrupt. What am I doing wrong?
This is how I build my connection string for SQLite.
Dim constr As String = "Data Source=""" & FullFilePath & """;Pooling=true;FailIfMissing=false"
Think you are just missing the Double Quotes around the path.
Public Function ConnExist(strDB) As Boolean
Dim cs As String
Dim cnn As New SQLiteConnection
Dim cmd As New SQLiteCommand
cs = "Data Source=" & strDB & ";Version=3;New=False;"
If (IO.File.Exists(strDB)) Then
cnn = New SQLiteConnection(cs)
Try
cnn.Open()
cmd = cnn.CreateCommand()
cmd.CommandText = "SELECT * FROM tblSettings"
cmd.ExecuteNonQuery()
cnn.Close()
cmd.Dispose()
cnn.Dispose()
Catch ex As Exception
Return False
Exit Function
End Try
Else
Return False
Exit Function
End If
Return True
End Function

How to handle database connectivity in entire project

I have created a function in a module to connect to database for a windows application
Imports System.Data.SqlClient
Module mod_main
Public Function connectDB() As SqlConnection
Dim Connection As New SqlConnection
Try
If Connection.State = ConnectionState.Open Then
Connection.Close()
End If
If IntegratedSecurity Then
Connection.ConnectionString = "Data Source = " & server & ";Initial Catalog = " & db & ";Connection TimeOut =0;Integrated Security=True"
Else
Connection.ConnectionString = "Data Source = " & server & ";Initial Catalog = " & db & ";Connection TimeOut =0;User ID='" & usr & "';Password='" & pwd & "'"
End If
Connection.Open()
Return Connection
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Function
End Module
I have so many functions and classes that uses plethora of db activities for that I use aforementioned connection function.For exmample:
Public Sub FillComboBox(ByVal ComboBox As C1.Win.C1List.C1Combo, ByVal Query As String, ByVal DisplayMember As String, ByVal ValueMember As String)
Dim SourceDataSet As New DataSet
Dim adapter As New SqlDataAdapter(Query, connectDB) /*Assigning connection here */
adapter.Fill(SourceDataSet)
ComboBox.DataSource = SourceDataSet.Tables(0)
ComboBox.ColumnHeaders = False
ComboBox.ColumnWidth = 0
ComboBox.ExtendRightColumn = True
ComboBox.DisplayMember = DisplayMember
ComboBox.ValueMember = ValueMember
End Sub
Since I'm a beginner in programming my question is , Is this a correct way of handling db connection?
I suggest you to make following changes:
make Connection as public for global accessibility
save connection string in config file and access it from there
need not to close and re open connection open connection only when there is no available connection
In your case all time it creates a new connection when the function is
invoked since you are declaring and initializing connection inside the
function. so checking connection state is meaning less:
so your function looks like following:
public Connection As New SqlConnection
Public Function connectDB() As SqlConnection
Try
Dim Constr As String =""
If IntegratedSecurity Then
Constr = ConfigurationManager.AppSetting("IconnectionString")
Else
Constr = ConfigurationManager.AppSetting("connectionString")
End If
If Connection Is Nothing Then
Connection = New SqlConnection(Constr)
End If
If Connection.State <> ConnectionState.Open Then
Connection.Open()
End If
Return Connection
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Function

Piping the results of a stored procedure to .NET text box

I have a Winform that simply contains a textbox object, which I'm trying to use as a repository for the results of a T-SQL stored procedure. Here is the code I'm using to connect to the database and run the stored procedure.
The SP seems to be running correctly, however it's not returning the information to the textbox in the way I'm expecting. It's not updating the text property at all.
Public Function ConnectToSQL() As String
Dim con As New SqlConnection
Dim reader As SqlDataReader
Try
con.ConnectionString = ("Data Source=" & Utilnamespace.SQLSvr & ";Database=Master" & ";integrated security=SSPI;")
Dim cmd As New SqlCommand("sp_whoisactive", con)
con.Open()
reader = cmd.ExecuteReader()
While reader.Read()
txtSQL.Text = String.Format("{0}", _
reader(0))
End While
Catch ex As Exception
MessageBox.Show("Error while connecting to SQL Server. " & ex.Message)
Finally
con.Close()
End Try
Return "Done"
End Function
What am I doing wrong here?
Shouldn't you be concatenating?
While reader.Read()
txtSQL.Text += String.Format("{0}", _
reader(0))
End While

Update database using ODBC

Here is my sub for updating a Database using ODBC:
Public Sub UpdateDatabase(ByVal sql As String, ByVal parameters() As OdbcParameter)
Dim connectionString As String = "dsn=" & ODBC & ";uid=" & UID & ";pwd="
Try
Using conn As OdbcConnection = New OdbcConnection(connectionString)
Dim adapter As New OdbcDataAdapter(sql, conn)
For Each parameter As OdbcParameter In parameters
adapter.InsertCommand.Parameters.Add(parameter)
Next
conn.Open()
adapter.InsertCommand.ExecuteNonQuery()
End Using
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
End Sub
Here is an example calling it with empty parameters:
Dim query As String = "INSERT INTO F_ARTICLE (AR_Ref) VALUES ('test')"
Dim parameters As OdbcParameter() =
{
}
UpdateDatabase(query, parameters)
But the following exception is shown:
NullReferenceException: Object reference not set to an instance of an object
Which seems to be triggered by this:
adapter.InsertCommand.ExecuteNonQuery()
Any idea what am I doing wrong here?
I still don't know why the previous sub didn't work, but this is how I solved it:
Public Sub UpdateDatabase(ByVal query As String, ByVal parameters() As OdbcParameter)
Dim connectionString As String = "dsn=" & ODBC & ";uid=" & UID & ";pwd="
Try
Using conn As OdbcConnection = New OdbcConnection(connectionString)
Using command As New OdbcCommand(query, conn)
For Each parameter As OdbcParameter In parameters
command.Parameters.Add(parameter)
Next
conn.Open()
command.ExecuteNonQuery()
End Using
End Using
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
End Sub