Update database using ODBC - vb.net

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

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)

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

Parameterizing sql in vb

I have this module call Procedure , and I want to parametrize it. I'm sending a string as the query to the procedure module . I look already in google but I could not find the answer to my problem.
Procedures.Insert("INSERT INTO Technician (tec_name, tec_email, rol_id) VALUES ('" & txt_tech.text & "', '" & txt_tech_email.text & "', " & cbo_tech_role.selectvalue.tostring & ")", "Technican Add Correct")
========================================
I will probably change it for .....
Procedures.Insert("INSERT INTO Technician (tec_name, tec_email, rol_id) VALUES ('#tech_name', '#tech_email', '#tech_role' ")", "Technican Add Correct")
================ But I dont know where I can Parametrized
Public Sub Insert(query As String, msg As String)
Dim cn As New SqlConnection(cs)
Dim cmd As New SqlCommand
Try
cn.Open()
With cmd
.CommandType = CommandType.Text
.CommandText = query
.Connection = cn
.Parameters.AddValueWith("#tech_name",txt_tech_name.text)
.Parameters.AddValueWith("#tech_email",txt_tech_email.text)
.Parameters.AddValueWith("#tech_rol",txt_tech_role.selectValue.tostring)
.ExecuteNonQuery()
End With
MessageBox.Show(msg, "INSERT", MessageBoxButtons.OK, MessageBoxIcon.Information)
Catch ex As Exception
MessageBox.Show(ex.Message.ToString, ". : : ERROR : : .", MessageBoxButtons.OK, MessageBoxIcon.Error)
Finally
If cn IsNot Nothing AndAlso cn.State <> ConnectionState.Closed Then
cn.Close()
cn = Nothing
End If
End Try
End Sub
Because I have a module that is separate from the main code , I'm not able to call the textboxes because they are separate from the main module ... any idea on how to do this ?? ... Dont be hard .. This is my 14 week working with VB.. :/
Add to the Insert function parameter for SqlParameters
Public Sub Insert(query As String, msg As String, params As SqlParameter())
Dim cn As New SqlConnection(cs)
Dim cmd As New SqlCommand
Try
cn.Open()
With cmd
.CommandType = CommandType.Text
.CommandText = query
.Connection = cn
If params IsNot Nothing AndAlso params.Count > 0 Then
.Parameters.AddRange(params)
End If
.ExecuteNonQuery()
End With
MessageBox.Show(msg,
"INSERT",
MessageBoxButtons.OK,
MessageBoxIcon.Information)
Catch ex As Exception
MessageBox.Show(ex.Message.ToString, ". : : ERROR : : .",
MessageBoxButtons.OK,
MessageBoxIcon.Error)
Finally
If cn IsNot Nothing AndAlso cn.State <> ConnectionState.Closed Then
cn.Close()
cn = Nothing
End If
End Try
End Sub
Then use it like this:
Dim query As String = "INSERT INTO Technician (tec_name, tec_email, rol_id) VALUES (#tech_name, #tech_email, #tech_role)"
Dim msg As String = "Technican Add Correct"
Dim params As SqlParameter() = {New SqlParameter("#tech_name",txt_tech_name.text),
New SqlParameter("#tech_email",txt_tech_email.text),
New SqlParameter("#tech_rol",txt_tech_role.selectValue.tostring)}
Procedures.Insert(query, msg, params)
Using array of SqlParameter give you a possibility for using same function with parameter type other then string
You can have it this way... it works for me.
String query = "INSERT INTO Technician(tec_name, tec_email, rol_id) VALUES(#tech_name, #tech_email, #tech_rolr)"
params = {"tech_name", "tech_email", "tech_rolr"}
values = {"" & txt_tech_name.text, "" & txt_tech_email.text, "" & txt_tech_role.selectValue.tostring()}
SaveUpdateDelete(query, params, values)
under module, you can put this
Public params() As String
Public values() As String
Public Sub SaveUpdateDelete(ByVal sql As String, ByVal parameters() As String, ByVal Values() As String)
If con.State = ConnectionState.Open Then
con.Close()
End If
con.Open()
command = New MySqlCommand(sql, con)
For i = 0 To parameters.Count - 1
command.Parameters.AddWithValue("#" & parameters(i).ToString, Values(i))
Next
command.CommandText = sql
command.ExecuteNonQuery()
con.Close()
End Sub
the method SaveUpdateDelete is applicable for adding, updating and deleting data.. your code will only differ in query... "insert, update, delete"