SQLite in vb 2010 - vb.net

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

Related

VB.net Is possibile ti use a THREAD to speed up a query? (Re-question from #Livio)

I try to ask this question from the user #Livio. Hope that's the right way!
I have a form with 6 textbox. Every textbox Is populated from a query. This took a long time to show the form.
Using a THREAD to speed up the operation Is a good idea?
DBConn.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;" & "Data Source=" & Para1 & "\F5C DRAGG_be.mdb;"
Try
DBConn.Open()
Catch ex As Exception
MsgBox(ex.Message)
MsgBox(ex.ToString)
End Try
RecuperoNPG("Provider=Microsoft.ACE.OLEDB.12.0;" & "Data Source=" & Para1 & "\F5C DRAGG_be.mdb;")
And the sub where the query phisically is :
Public Function RecuperoNPG(ByVal connString As String) As Integer
Dim NPG As Int32 = 0
Dim sql As String = "SELECT Count(RegProduzione.MATRICOLA) AS C_MATRICOLA FROM RegProduzione WHERE Regproduzione.Data = #" & T_Data_Conv.Text & "#"
Using Conn As New OleDb.OleDbConnection(connString)
Dim Cmd As New OleDb.OleDbCommand(sql, Conn)
Try
Conn.Open()
NPG = Convert.ToInt32(Cmd.ExecuteScalar())
T_MotGiorno.Text = NPG
Catch ex As Exception
Console.WriteLine(ex.Message)
End Try
End Using
Return NPG
End Function

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)

Best way to deal with Open Datareader Error (vb.net and mysql)

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.

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

How to use ACE OLEDB to import Excel data into VB?

Originally I was using Office Interop to import data, but that was a headache and a half for both me and my computer. Right now I'm attempting to load it with ACE, but my data grid isn't being populated. Once that's up and running I need to know how to use that data in other ways, and how to grab specific cells of data from that DataSet. I'm using Visual Studio 2008, by the way.
Right now I have...
Public Function funcUpdate(ByVal sFileLoc As String) As Boolean
'Determine connection string properties
Dim dbProperty As String
If updFileExt = ".xlsx" Then
dbProperty = "Excel 12.0 Xml;HDR=No"
ElseIf updFileExt = ".xls" Then
dbProperty = "Excel 12.0;HDR=No"
Else
MessageBox.Show("FATAL: File type error on updater", "OHGAWDNO", MessageBoxButtons.OK, MessageBoxIcon.Error)
updateTerm()
Return False
End If
Dim dbConn As New OleDb.OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & updFile & ";Extended Properties=" & dbProperty & ";")
Dim dbCommand As New OleDb.OleDbDataAdapter("select * from [sheet1$]", dbConn)
Dim dtSet As New DataSet
Try
dbCommand.TableMappings.Add("Table", "ExcelTest")
dbCommand.Fill(dtSet)
Form1.DataGrid1.DataSource = dtSet.Tables(0)
Catch exlErr As Exception
Finally
dbConn.Close()
End Try
updateTerm()
End Function
Try to do this.
Dim path As String = "c:\example.xlsx"
Dim constr As String = [String].Format("Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties=""Excel 12.0 Xml;" & _
"HDR=YES;IMEX=1;""", path)
Dim adapter As New OleDbDataAdapter
Using cn As New System.Data.OleDb.OleDbConnection(constr)
Try
cmdselcet = New OleDbCommand("SELECT * FROM [Sheet1$]", cn)
cn.Open()
adapter.SelectCommand = cmdselcet
Dim ds As DataSet
ds = New DataSet
'Display
adapter.Fill(ds)
DataGridView1.DataSource = ds.Tables(0)
MsgBox("Done!")
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Using