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

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

Related

odbc reader for csv in vb.net

I'm writing a program that should handle million of datasets in csv in a short time, my idea was to use odbc because of performance reasons, therefore i read all the data with odbc and save it in memory, thereafter i add parameters and insert it in sql db, here is my code so far:
Using connection As New OdbcConnection("jdbc:odbc:Driver={Microsoft Text Driver (*.txt; *.csv)};" & filePath & "Extensions=csv;Persist Security Info=False;")
Dim reader As OdbcDataReader
Dim i As Integer
Dim r As SeekZeilen
Dim TextFileTable As DataTable = Nothing
Dim line As String = reader.Read()
Me.ParseString(line)
Dim memStream As New MemoryStream(Encoding.Default.GetBytes(line))
Using TextFileReader As New Microsoft.VisualBasic.FileIO.TextFieldParser(memStream)
TextFileReader.TextFieldType = FileIO.FieldType.Delimited
TextFileReader.SetDelimiters(";")
r.erste_Zeile = TextFileReader.ReadFields()
If TextFileTable Is Nothing Then
TextFileTable = New DataTable("TextFileTable")
For i = 0 To r.erste_Zeile.Length - 1
Dim Column As New DataColumn(r.erste_Zeile(i))
Column.ReadOnly = True
TextFileTable.Columns.Add(Column)
Next
End If
DataGridView1.DataSource = TextFileTable
End Using
While reader.HasRows
line = reader.Read()
Me.ParseString(line)
memStream = New MemoryStream(Encoding.Default.GetBytes(line))
Using TextFileReader As New Microsoft.VisualBasic.FileIO.TextFieldParser(memStream)
TextFileReader.TextFieldType = FileIO.FieldType.Delimited
TextFileReader.SetDelimiters(";")
DataGridView1.DataSource = TextFileTable
Try
r._Rest = TextFileReader.ReadFields()
ReplaceChars(r._Rest)
If Not r._Rest Is Nothing Then
Dim oSQL As New DBUmgebung.cdb.SQL()
oSQL.init()
AddParameters(oSQL, r)
oSQL.ausfuehrenSQL(DBUmgebung.cdb.KSQLCommand.INSERT, _table, "")
Dim dtRow As DataRow = TextFileTable.NewRow
For i = 0 To r._Rest.Length - 1
dtRow(i) = r._Rest(i).ToString()
Next
TextFileTable.Rows.Add(dtRow)
DataGridView1.Refresh()
Application.DoEvents()
End If
Catch ex As Microsoft.VisualBasic.FileIO.MalformedLineException
MsgBox("Error! " & ex.Message & _
"")
Catch sqlEx As SqlException
MessageBox.Show(sqlEx.Message)
rtbSql.Focus()
Exit For
Catch ex As Exception
MessageBox.Show(ex.Message)
rtbSql.Focus()
Exit For
End Try
End Using
End While
reader.Close()
End Using
the problem is that i get null pointer exception for a unknown reason, does anyone have idea what i did wrong? is it probably because my odbc reader is not properly initialized?
Try this. This will read the csv file as all text into a datatable. Once in the Datatable you could then insert the records into SQL. You can always adjust this to handle multiple csv files.
Friend Shared Function GetExcelFile(ByVal strFileName As String, ByVal strPath As String) As DataTable
Try
Dim dt As New DataTable
Dim ConStr As String = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & strPath & ";Extended Properties=""Text;HDR=Yes;FMT=Delimited\"""
Dim conn As New OleDb.OleDbConnection(ConStr)
Dim da As New OleDb.OleDbDataAdapter("Select * from " & strFileName, conn)
da.Fill(dt)
Return dt
Catch ex As Exception
Return Nothing
End Try
End Function

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

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

There is already an open DataReader associated with this Connection which must be closed first VB.NET

I get this error message
"There is already an open DataReader associated with this Connection
which must be closed first"
Please help me
My code is:
Public Sub update_qty(ByVal qry1 As String)
Dim dr As MySqlDataReader 'SQLiteDataReader
Dim comm As MySqlCommand 'SQLiteCommand
Try
comm = New MySqlCommand(qry1, conn)
dr = comm.ExecuteReader()
Catch ex As Exception
MsgBox(ex.Message)
End Try
Do While dr.Read()
exe_query("call cargosys.paymentsAdd('" & var1 & "', " & dr("inNo") & ")")
Loop
dr.Close()
End Sub
Public Sub exe_query(ByVal qry As String) As String
Dim cmd As MySqlCommand
Try
cmd = New MySqlCommand(qry, conn)
cmd.ExecuteNonQuery()
Catch ex As MySqlException
MessageBox.Show(ex.ToString)
End Try
End Sub
Your problem is that your code open a DataReader and then execute the SqlCommand when the DataReader read
Try to change this line:
dr = comm.ExecuteReader()
to:
dr = comm.ExecuteReader(CommandBehavior.CloseConnection)
More: DataReader CommandBehavior
Or change your connection string to enable MARS (Multiple Active Result Sets).
This setting will allow for the retrieval of multiple forward-only, read-only result sets on the same connection.
For example :
connectionString=
"Data Source=.\SQLEXPRESS;
AttachDbFilename=|DataDirectory|Northwind.MDF;
Integrated Security=True;
User Instance=True;
MultipleActiveResultSets=True"
More: MARS
EDIT
Since MARS keyword is not supported, try to change your code to this:
Public Sub update_qty(ByVal qry1 As String)
Dim dr As MySqlDataReader 'SQLiteDataReader
Dim comm As MySqlCommand 'SQLiteCommand
Try
comm = New MySqlCommand(qry1, conn)
dr = comm.ExecuteReader()
Catch ex As Exception
MsgBox(ex.Message)
End Try
Dim myList As New List(Of String)
Do While dr.Read()
myList.Add("call cargosys.paymentsAdd('" & var1 & "', " & dr("inNo") & ")")
Loop
dr.Close()
End Sub
Public Sub exe_query(myList As List(Of String))
Dim cmd As MySqlCommand
For Each query As String In myList
Try
cmd = New MySqlCommand(query, conn)
cmd.ExecuteNonQuery()
Catch ex As MySqlException
MessageBox.Show(ex.ToString)
End Try
Next
End Sub
Instead to doing DataReader.Read->SqlCommand.ExecuteNonQuery simultaneously, this code will be read all the data first and then run SqlCommand.ExecuteNonQuery.

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