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
Related
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
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)
My Project running on VS 2013 & MySQL, I have declared public variable conn as mysqlconnection and I use the same connection all over the project to perform any database operation.
Public conn As New MySqlConnection
Public Sub createConnection()
If conn.State = ConnectionState.Closed Then
conn.ConnectionString = parseConfigXML()
conn.Open()
End If
End Sub
Public Function parseConfigXML()
Try
Dim m_xmld As XmlDocument
Dim m_nodelist As XmlNodeList
Dim m_node As XmlNode
m_xmld = New XmlDocument()
m_xmld.Load("../../../appconfig.xml")
m_nodelist = m_xmld.SelectNodes("/app/config")
Dim hostname, dbname, dbuser, dbpassword As String
hostname = ""
dbname = ""
dbuser = ""
dbpassword = ""
For Each m_node In m_nodelist
hostname = m_node.ChildNodes.Item(0).InnerText.ToString
dbname = m_node.ChildNodes.Item(1).InnerText.ToString
dbuser = m_node.ChildNodes.Item(2).InnerText.ToString
dbpassword = m_node.ChildNodes.Item(3).InnerText.ToString
Next
Dim connectionString = "Database=" & dbname & "; Data Source=" & hostname & "; User Id=" & dbuser & ";Password=" & dbpassword & "; Character Set=utf8"
Return connectionString
Catch errorVariable As Exception
MsgBox("Oops, An error occured: " & errorVariable.ToString)
End Try
End Function
Whenever connection is required, I use it as follows:
Try
Dim query As String = "select * from tbl_lang where lang_status=1"
Dim cmd As New MySqlCommand(query, conn)
Dim dr As MySqlDataReader
dr = cmd.ExecuteReader
If dr.HasRows Then
Do While dr.Read
cmb.Items.Add(dr.GetString("lang_name"))
Loop
End If
cmb.SelectedItem = "English"
If Not dr.IsClosed Then dr.Close()
Catch ex As Exception
lbl_error.text="Oops, An error occured: " & ex.ToString
End Try
I always have this issue when the code is reused: There is already open datareader for this connection.
What is the best way to deal with it? someone had mentioned to use open new connection for every query and then close it. Somehow, I am not convinced with it as it may create performance issues.
Please suggest the best way to overcome the issue.
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
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