VB.NET - Closing Connection object and command object - vb.net

Please have a look at the code below:
Public Class Form1
Private _ConString As String
Private Sub Form1_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Dim objDR As SqlDataReader
Dim objCommand As SqlCommand
Dim objCon As SqlConnection
Dim id As Integer
Try
_ConString = ConfigurationManager.ConnectionStrings("TestConnection").ToString
objCon = New SqlConnection(_ConString)
objCommand = New SqlCommand("SELECT * FROM Person")
objCommand.Connection = objCon
objCon.Open()
objDR = objCommand.ExecuteReader(ConnectionState.Closed)
Do While objDR.Read
id = objDR("URN")
Loop
objDR.Close() 'line 16
Catch ex As Exception
throw
Finally
End Try
End Sub
End Class
The connection object is closed on line 16. Please have a look at the code below:
Private Sub Form1_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Dim objDR As SqlDataReader
Dim objCommand As SqlCommand
Dim objCon As SqlConnection
Dim id As Integer
Try
_ConString = ConfigurationManager.ConnectionStrings("TestConnection").ToString
objCon = New SqlConnection(_ConString)
objCommand = New SqlCommand("SELECT * FROM Person")
objCommand.Connection = objCon
objCon.Open()
Using objCon
Using objCommand
objDR = objCommand.ExecuteReader()
Do While objDR.Read
id = objDR("URN")
Loop
End Using
End Using
objDR.Close() 'line 16
Catch ex As Exception
throw
Finally
End Try
End Sub
I notice in both cases that the connection object and command object both still have state after they are closed (either by closing the data reader as per code sample 1 or moving outside the Using statement as per code sample 2). Could this be a source of a memory leak?

You should be doing something like this...
Using Conn as new SqlConnection(_ConString)
Dim cmd as New SqlCommand(Conn, "Select * FROM Person");
id = Convert.ToInt32(cmd.ExecuteScalar())
End Using
Wrap this in a try if you must, but only if you are going to handle it in some way. (A simple "Throw" is not handling anything.)
You are also using a DataReader (iterative, forward only) data access component to get a single value. You may want to use an ExecuteScalar() to simplify that code.
Aside from that, do not confuse "Disposed" as being the same as "Closed". The .NET framework manages garbage collection for you. If you want to dispose the connection and command objects, call .Dispose() on them (but the Using will take care of this for you!!!)

re: Could this be a source of a memory leak?
no, it shouldn't be.
also, this:
objDR = objCommand.ExecuteReader()
Do While objDR.Read
id = objDR("URN")
Loop
looks bad because it iterates through all the rows and overwriting the id values. The last row set ends up with the value in ID. You're taking one result from a set of more than one rows. If you just want the max(URN) from Person, you can write your command to return that result.

Related

i am currently getting this error, System.InvalidOperationException: 'Fill: SelectCommand.Connection property has not been initialized.'

Imports System.Data
Imports System.Data.OleDb
Imports System.Data.DataTable
Public Class Form1
Private Sub btnlogin_Click(sender As Object, e As EventArgs) Handles btnlogin.Click
Dim conn As New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\Katlego\Documents\LoginDb.accdb")
Dim cmd As New OleDbCommand("select * from logintable where username1=#username1 and password1=#password1, conn")
cmd.Parameters.Add("#username1", oleDbType:=OleDbType.VarChar).Value = txtusername.Text
cmd.Parameters.Add("#password1", oleDbType:=OleDbType.VarChar).Value = txtpassword.Text
Dim adapter1 As New OleDbDataAdapter(cmd)
Using logintable As New DataTable
Dim unused = adapter1.Fill(logintable)
If logintable.Rows.Count <= 0 Then
MsgBox("error username or password")
Else
MsgBox("login sucessfull")
End If
End Using
End Sub
You need to open the connection first
conn.Open()
There's a typo when you are initializing cmd object. You include the conn object inside the connection string. So the cmd object is missing a connection object.
Dim cmd As New OleDbCommand("select * from logintable where username1=#username1 and password1=#password1, conn")
Should be:
Dim cmd As New OleDbCommand("select * from logintable where username1=#username1 and password1=#password1", conn)
It is usually a good idea to separate you user interface code (where you click buttons and show message boxes) from your database code.
Connections, Commands and DataAdapters need to be disposed so they can release their unmanaged resources. Using...End Using blocks will do this for us.
Since you only want to know if the record exits you can just get the count. You had a typo in your command text. The closing quote included the conn.
We don't need DataTable or DataAdapter. That single piece of data only requires an ExecuteScalar which returns an Object so we need the CInt.
Private Sub btnlogin_Click(sender As Object, e As EventArgs) Handles btnlogin.Click
If IsLoginValid(txtusername.Text, txtpassword.Text) Then
MsgBox("login sucessfull")
Else
MsgBox("error username or password")
End If
End Sub
Private Function IsLoginValid(uname As String, pword As String) As Boolean
Dim count As Integer
Using conn As New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\Katlego\Documents\LoginDb.accdb"),
cmd As New OleDbCommand("select Count(*) from logintable where username1=#username1 and password1=#password1;", conn)
cmd.Parameters.Add("#username1", OleDbType.VarChar).Value = uname
cmd.Parameters.Add("#password1", OleDbType.VarChar).Value = pword
conn.Open()
count = CInt(cmd.ExecuteScalar)
End Using
If count = 1 Then
Return True
End If
Return False
End Function
There is still a big problem with the code. Passwords should NEVER be stored as plain text. They need to be salted and hashed but that is beyond the scope of this question.

OleDbException was unhandled, syntax error in WHERE clause?

Having trouble with a persistent error. My form allows the user to see a list of elements in a particular group. The input for group number is a combobox called groupbox and the output is a combobox called ElementResults. I am getting the error on the line: GroupSearch.ExecuteNonQuery()
Imports System.Data.OleDb
Public Class ElementsSearch
Public Shared connectionString As String = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Documents and Settings\A\My Documents\Visual Studio 2010\Projects\A2\Element.accdb;Persist Security Info=False;"
Public Shared ElementsTable
Private Sub Button2_Click(sender As System.Object, e As System.EventArgs) Handles Button2.Click
Dim Search As New OleDbConnection(connectionString)
Search.Open()
Dim SearchCriteria As String
SearchCriteria = Groupbox.Text
Dim query As String = "SELECT * From ElementsTable WHERE Group='" & SearchCriteria & "'"
Dim GroupSearch As New OleDbCommand(query, Search)
GroupSearch.ExecuteNonQuery()
Dim reader As OleDbDataReader = GroupSearch.ExecuteReader()
ElementResults.Text = Convert.ToString(reader("Name"))
End Sub
End Class
You define the field group which is a reserved keyword.
Try [group] instead like in this sample:
SELECT * From ElementsTable WHERE [Group]='aaa'
To avoid all the errors you're getting, consider changing your code to something like this:
Using connection As New OleDbConnection(connectionString)
connection.Open()
Using command As New OleDbCommand("SELECT * From ElementsTable WHERE [Group]=#Group", connection)
command.Parameters.AddWithValue("#Group", SearchCriteria)
Using reader As OleDbDataReader = command.ExecuteReader()
Do While reader.Read()
ElementResults.Text = reader.GetString("Name")
Loop
End Using
End Using
End Using

Reading tables using OleDBConnection

First off, i'm new to VB and this is my first project using OleDBConnection.
ok, so i'm trying to the most simple thing using oleDbConnection (i assume). I just want to read data from a table in the Access DB and display that information to dropboxes (or anything) in my winForm.
Public Class QueManger
Dim dbConnection As OleDbConnection
Dim dbCommand As OleDbCommand
Dim dbDataAdapter As OleDbDataAdapter
Dim ConnectString As String = "Provider = Microsoft.Jet.OLEDB.4.0;" & "Data Source = \\atrts10\F:\Applications\ATRTaxCert\Development\mtaylor\TaxCert_be_test.accdb"
Dim dtMain As DataTable
Private Sub QueManger_Load(sender As Object, e As EventArgs) Handles MyBase.Load
StatusName()
End Sub
Private Sub StatusName()
Dim taxconn As OleDbConnection
Try
taxconn = New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=\\atrts10\F:\Applications\ATRTaxCert\Development\mtaylor\TaxCert_be_test.accdb")
Dim taxcmd As OleDbCommand = taxconn.CreateCommand
taxcmd.CommandText = "SELECT StatusName FROM Status ORDER BY StatusName"
Dim rdr2 As OleDbDataReader
If taxconn.State = ConnectionState.Closed Then
taxconn.Open()
End If
rdr2 = taxcmd.ExecuteReader
'boxStatus.Items.Add("All")
While rdr2.Read()
boxClient.Items.Add(rdr2.Item("StatusName"))
End While
Catch ex As Exception
Finally
taxconn.Close()
End Try
End Sub
The error comes when it tries to run the "taxconn.Open()" function.
The error says "The Microsoft Access database engine cannot open or write to the file '\atrts10\F:\Applications\ATRTaxCert\Development\mtaylor\TaxCert_be_test.accdb'. It is already opened exclusively by another user, or you need permission to view and write its data."
any thoughts?
try to close the opened table first in access if you are editing them, and try to add "#" before the string to use your path.
then try to use this connection string;
string connectionString = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + yourDataBasePath + ";Persist Security Info=False;";

ExecuteReader CommandText property has not been properly initialized

First of all sorry if some of the code isn't right. I'm still new to using sql on vb.net
I have the following code:
Imports MySql.Data.MySqlClient
Imports System.Data.SqlClient
Public Class Form1
Private Sub btnLoad_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnLoad.Click
Dim objConn As MySqlConnection
Dim objDataset As New DataSet
Dim objDataAdapter As MySqlDataAdapter
Dim myCommand As MySqlCommand
Dim sqlConn As String
objConn = New MySqlConnection("server=localhost;userid=root;database=attendance_system")
myCommand = objConn.CreateCommand
objConn.Open()
Dim objReader As MySqlDataReader = myCommand.ExecuteReader
sqlConn = "SELECT student_name FROM profile"
objDataAdapter = New MySqlDataAdapter(sqlConn, objConn)
objDataAdapter.Fill(objDataset, "profile")
MsgBox("The Connection is Now 'OPEN'")
objReader.Read()
TextBox1.Text = objReader("student_name")
objReader.Close()
objConn.Close()
End Sub
End Class
I am using MySQL connector via vb.net in phpmyadmin and have set a database with records.
The connection string is working, but my problem is when I try to click the button to load the data in the textbox, I keep getting:
The CommandText property has not been properly initialized."
The error is on this line:
"Dim objReader As MySqlDataReader = myCommand.ExecuteReader"
I've tried a lot of fixes that I've found on this site and the others as well.
This is the problem:
Dim objReader As MySqlDataReader = myCommand.ExecuteReader
sqlConn = "SELECT student_name FROM profile"
You're declared the SQL after you've tried executing the query (and even then you don't set it as the SQL for the command). How would you expect that to work? Additionally, sqlConn is a very strange name for a variable declaring the SQL - I'd expect it to be a connection.
It looks like you're trying to mix too very different ways of fetching data:
Reading directly from the reader
Filling a DataSet with a data adapter
You shouldn't be mixing them like that. Work out which you actually want to do, take out all the code related to the other style, and then make sure you're doing everything in a sensible order.
From MySqlCommand Class and the example given as
Public Sub ReadMyData(myConnString As String)
Dim mySelectQuery As String = "SELECT * FROM Test.Dept"
Dim myConnection As New MySqlConnection(myConnString)
Dim myCommand As New MySqlCommand(mySelectQuery, myConnection)
myConnection.Open()
Dim myReader As MySqlDataReader = myCommand.ExecuteReader()
Try
While myReader.Read()
Console.WriteLine(myReader.GetInt32(0).ToString() + ", " _
+ myReader.GetString(1))
End While
Finally
' always call Close when done reading.
myReader.Close()
' always call Close when done with connection.
myConnection.Close()
End Try
End Sub
Your command object is missing the select statement.

Error: A SQLParamenter wtih ParameterName #myparm is not contained by this SQLParameter Collection

Good Morning,
I'm working on an ASP.NET 3.5 webforms application and have written the following code:
Protected Sub btnSubmit_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnSubmit.Click
Dim connectionString As String = WebConfigurationManager.ConnectionStrings("Diel_inventoryConnectionString").ConnectionString
Dim con As New SqlConnection(connectionString)
Dim adapter1 As New SqlDataAdapter
adapter1.SelectCommand = New SqlCommand
adapter1.SelectCommand.CommandType = CommandType.StoredProcedure
adapter1.SelectCommand.CommandText = "PartSproc"
Dim parmNSN As New SqlParameter("#NSN", SqlDbType.NVarChar)
Dim parmName As New SqlParameter("#PartName", SqlDbType.NVarChar)
txtNSN.Text = adapter1.SelectCommand.Parameters("#NSN").Value
txtSearch.Text = adapter1.SelectCommand.Parameters("#PartName").Value
Dim dt As New DataTable()
adapter1.Fill(dt)
MySearch.DataSource = dt
MySearch.DataBind()
End Sub
When I run the page, I receive the error A SQLParameter with #NSN is not contained by this SQLParameter Collection. I tried using apostrophes around the #NSN and #PartName but that does not work either and presents expression expected error.
How might I rectify the above code so that it references the #NSN and #PartName parameters correctly?
EDIT: New Code below
Protected Sub btnSubmit_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnSubmit.Click
Dim connectionString As String = WebConfigurationManager.ConnectionStrings("Diel_inventoryConnectionString").ConnectionString
Dim con As New SqlConnection(connectionString)
Dim cmd As New SqlCommand("PartSproc", con)
cmd.CommandType = CommandType.StoredProcedure
Dim adapter1 As New SqlDataAdapter
Dim parmNSN As New SqlParameter("#NSN", SqlDbType.NVarChar)
Dim parmName As New SqlParameter("#PartName", SqlDbType.NVarChar)
adapter1.SelectCommand.Parameters.Add(parmNSN)
adapter1.SelectCommand.Parameters.Add(parmName)
adapter1.SelectCommand.Parameters("#NSN").Value = txtNSN.Text
adapter1.SelectCommand.Parameters("#PartName").Value = txtSearch.Text
Using con
Dim dt As New DataTable()
adapter1.SelectCommand = cmd
adapter1.Fill(dt)
MySearch.DataSource = dt
MySearch.DataBind()
End Using
End Sub
I now receive an error Object reference not set to an instance of an object referencing the add parameter parmNSN. Do I really need those to add paraameter statements since I've already set them equal to the text boxes below?
Thanks,
Sid
I think you accidentally transposed the assignment of the parameter values - try this instead:
adapter1.SelectCommand.Parameters("#NSN").Value = txtNSN.Text
adapter1.SelectCommand.Parameters("#PartName").Value = txtSearch.Text
Did you read the error message? The Sqlparameter you create is never added to the Sqlparameter collection of the command ;) This is what the error message also ells you.
You create the parameters, but they "hang in the air" so to say.
To add to what Andrew & TomTom said, you need to add the parameters to the parameters collection of SelectCommand.
Something like
adapter1.SelectCommand.Parameters.Add(parmNSN);
adapter1.SelectCommand.Parameters.Add(parmName);
Do this before you make a call to ExecuteReader() or ExecuteScalar