Using SQLDataReader instead of recordset - vb.net

I am new to this and had this question. Can I use SQLDataReader instead of a Recordset. I want to achieve the following result in an SQLDataReader.
Dim dbConn As New ADODB.Connection
Dim rs As New ADODB.Recordset
Dim sqlstr As String = "SELECT Name,Status FROM table1 WHERE id=" + item_id.Value.ToString
rs.Open(SQL, dbConn)
While Not rs.EOF
txtName.Text = rs.Fields.Item("Name").Value
ddlstatus.SelectedIndex = 1
rs.MoveNext()
End While
rs.Close()
rs = Nothing
dbConn.Close()
dbConn = Nothing
Can I replace recordset with SQLDataReader and if I can can you please show me the changes in code?

Its highly recommend that you use the using pattern:
Dim sConnection As String = "server=(local);uid=sa;pwd=PassWord;database=DatabaseName"
Using Con As New SqlConnection(sConnection)
Con.Open()
Using Com As New SqlCommand("Select * From tablename", Con)
Using RDR = Com.ExecuteReader()
If RDR.HasRows Then
Do While RDR.Read
txtName.Text = RDR.Item("Name").ToString()
Loop
End If
End Using
End Using
Con.Close()
End Using

You will have to swap out a few things, something similar to the following.
Here is an example, you will need to modify this to meet your goal, but this shows the difference.
I also recommend using a "Using" statement to manage the connection/reader. Also, a parameterized query.
Dim sConnection As String = "server=(local);uid=sa;pwd=PassWord;database=DatabaseName"
Dim objCommand As New SqlCommand
objCommand.CommandText = "Select * From tablename"
objCommand.Connection = New SqlConnection(sConnection)
objCommand.Connection.Open()
Dim objDataReader As SqlDataReader = objCommand.ExecuteReader()
If objDataReader.HasRows Then
Do While objDataReader.Read()
Console.WriteLine(" Your name is: " & Convert.ToString(objDataReader(0)))
Loop
Else
Console.WriteLine("No rows returned.")
End If
objDataReader.Close()
objCommand.Dispose()

Dim rdrDataReader As SqlClient.SqlDataReader
Dim cmdCommand As SqlClient.SqlCommand
Dim dtsData As New DataSet
Dim dtbTable As New DataTable
Dim i As Integer
Dim SQLStatement as String
msqlConnection.Open()
cmdCommand = New SqlClient.SqlCommand(SQLStatement, msqlConnection)
rdrDataReader = cmdCommand.ExecuteReader()
For i = 0 To (rdrDataReader.FieldCount - 1)
dtbTable.Columns.Add(rdrDataReader.GetName(i), rdrDataReader.GetFieldType(i))
Next
dtbTable.BeginLoadData()
Dim values(rdrDataReader.FieldCount - 1) As Object
While rdrDataReader.Read
rdrDataReader.GetValues(values)
dtbTable.LoadDataRow(values, True)
End While
dtbTable.EndLoadData()
dtsData.Tables.Add(dtbTable)
msqlConnection.Close()
Return dtsData

Related

VB.Net - ExecuteReader: CommandText property has not been initialized

I know there are some threads about this topic, but for some reason nothing of these things given there didn't work for me. So that is my code:
Dim strAccSQL As String = "SELECT nUserNo FROM dbo.tUser WHERE sUserID='" & AccountID.Text & "';"
Dim catCMDAcc As SqlCommand = New SqlCommand(strAccSQL, AccCon)
Dim myAccountReader As SqlDataReader = catCMDAcc.ExecuteReader()
While myAccountReader.Read
AccountNo.Text = myAccountReader(0)
End While
myAccountReader.Close()
Con.Close()
Con.Open()
Dim strSQL2 As String
Dim catCMD As SqlCommand = New SqlCommand(strSQL2, Con)
Dim myReader As SqlDataReader = catCMD.ExecuteReader()
InfoTextBox.Text &= Environment.NewLine & Now & " Account: " & AccountID.Text & " Found"
CharacterName.Properties.Items.Clear()
While myReader.Read()
CharacterName.Properties.Items.Add(myReader(0))
End While
myReader.Close()
AccCon.Close()
Con.Close()
Anyone got an idea for my problem?
As the errormessage states, your CommandText is empty string here (strSQL2):
Dim strSQL2 As String
Dim catCMD As SqlCommand = New SqlCommand(strSQL2, Con)
Dim myReader As SqlDataReader = catCMD.ExecuteReader()
You cannot execute an empty sql-clause.

How to catch oledbdatareader errors

I have this code i wrote to find out if a record exists in data base. It works well when record is found. If it isn't, it brings up an error. I would like the error to be caught in a messagebox that states "record not found" instead.
Dim findprinc As String = TextBox1.Text.Substring(0, 16)
MsgBox(findprinc)
sql = "Select RealID from Dets where ID like '%" & findprinc & "%'"
MsgBox(sql)
Dim conn As New OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0; Persist Security Info=false; Data Source=..\new.mdb")
conn.Open()
Dim cmd As New OleDbCommand(sql, conn)
Dim numeri As OleDbDataReader = cmd.ExecuteReader
numeri.Read()
Dim findprinc As String = TextBox1.Text.Substring(0, 16)
MsgBox(findprinc)
Sql = "Select RealID from Dets where ID like '%" & findprinc & "%'"
MsgBox(Sql)
Dim conn As New OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0; Persist Security Info=false; Data Source=..\new.mdb")
conn.Open()
Dim cmd As New OleDbCommand(Sql, conn)
Dim numeri As OleDbDataReader = cmd.ExecuteReader
Dim recordFound As Boolean = False
While numeri.Read
recordFound = True
End While
If recordFound = False Then
MsgBox("Record Not Found")
End If

Sending updates from datagridview to existing row in database

I am retrieving records from a database with the following code.
Dim SearchID As Integer = teacherID
Dim NewStudentID As Integer = studentID
Dim DisplayTable As New DataTable()
Dim da As New OleDbDataAdapter()
Dim sqlquery As String = ("select * from tblAppointments WHERE TeacherID =" & teacherID & "")
If conn.State = ConnectionState.Closed Then
conn.Open()
End If
Try
da.SelectCommand = New OleDbCommand(sqlquery, conn)
da.Fill(Finalds, "Display")
DisplayTable = Finalds.Tables("Display")
DisplayTable.Columns.Remove("Instrument")
DisplayTable.Columns.Remove("Room")
DisplayTable.Columns.Remove("TeacherID")
Registersgridview.DataSource = DisplayTable
Registersgridview.Columns(0).Visible = False
conn.Close()
Catch ex As Exception
MsgBox("There are no appointments in the database for " + Tutorcombox.Text)
End Try
It also there then added to a datagridview and certain columns are removed and some are hidden aswell.
Because its essentially a register, when the use clicks on the datagridview field that is a boolean it changes from false to true. I have been trying to send this back to the database, but have had no luck. I have tried the following :
Dim dt As DataTable = New DataTable("SendTable")
Dim row As DataRow
dt.Columns.Add("appID", Type.GetType("System.Int32"))
dt.Columns.Add("Present", Type.GetType("System.Boolean"))
For i = 0 To Registersgridview.Rows.Count - 1
row = dt.Rows.Add
row.Item("appID") = Registersgridview.Rows(i).Cells(0)
row.Item("Present") = Registersgridview.Rows(i).Cells(5)
Next
If conn.State = ConnectionState.Closed Then
conn.Open()
End If
Dim sqlquery As String = "Update tblAppointments SET Present = #Present WHERE appID = #appID"
Dim sqlcommand As New OleDbCommand
For Each newrow As DataRow In dt.Rows
With sqlcommand
.CommandText = sqlquery
.Parameters.AddWithValue("#Present", newrow.Item(1))
.Parameters.AddWithValue("#appID", newrow.Item(0))
.ExecuteNonQuery()
End With
conn.Close()
Next
But have had no luck with doing so, as it crashes without an error.
Can anyone help?
I solved the problem myself, if any of you are having similar problems here is the solution
Dim dt As DataTable = New DataTable("SendTable")
Dim row As DataRow
dt.Columns.Add("appID", Type.GetType("System.Int32"))
dt.Columns.Add("Present", Type.GetType("System.Boolean"))
For i = 0 To Registersgridview.Rows.Count - 1
Dim appID As Integer = Registersgridview.Rows(i).Cells(0).Value
Dim present As Boolean = Registersgridview.Rows(i).Cells(4).Value
row = dt.Rows.Add
row.Item("appID") = appID
row.Item("Present") = present
Next
If conn.State = ConnectionState.Closed Then
conn.Open()
End If
Dim sqlquery As String = "UPDATE tblAppointments SET Present = #Present WHERE appID = #appID"
Dim sqlcommand As New OleDbCommand
For Each newrow As DataRow In dt.Rows
With sqlcommand
.CommandText = sqlquery
.Parameters.AddWithValue("#Present", newrow.Item(1))
.Parameters.AddWithValue("#appID", newrow.Item(0))
.Connection = conn
.ExecuteNonQuery()
End With
Next
conn.Close()
Registersgridview.DataSource = Nothing
dt.Clear()
try this:
Dim dt As DataTable = New DataTable("SendTable")
Dim row As DataRow
dt.Columns.Add("appID", Type.GetType("System.Int32"))
dt.Columns.Add("Present", Type.GetType("System.Boolean"))
For i = 0 To Registersgridview.Rows.Count - 1
row = dt.Rows.Add
row.Item("appID") = Registersgridview.Rows(i).Cells(0)
row.Item("Present") = Registersgridview.Rows(i).Cells(5)
Next
If conn.State = ConnectionState.Closed Then
conn.Open()
End If
Dim sqlquery As String = "Update tblAppointments SET Present = #Present WHERE appID = #appID"
Dim sqlcommand As New OleDbCommand
For Each newrow As DataRow In dt.Rows
With sqlcommand
.CommandText = sqlquery
.Parameters.AddWithValue("#Present", newrow.Item(5))
.Parameters.AddWithValue("#appID", newrow.Item(0))
.ExecuteNonQuery()
End With
conn.Close()
Next

TransactionScope committing on each loop

Please see the code below:
Private Sub TransactionExample3()
Dim objDR As SqlDataReader
Dim objCommand As SqlCommand, objCommand2 As SqlCommand
Dim objCon As SqlConnection
Dim objCon2 As SqlConnection
Dim id As Integer
Dim list As List(Of Integer) = New List(Of Integer)
Try
_ConString = "Data Source=databaseserver;Initial Catalog=Person;User ID=username;Password=password;MultipleActiveResultSets=True"
list.Add(1)
list.Add(2)
list.Add(3)
For Each i As Integer In list
Using trans = New TransactionScope()
objCon2 = New SqlConnection(_ConString)
objCon2.Open()
objCommand2 = New SqlCommand()
objCommand2.Connection = objCon2
Using objCon2
objCommand2.CommandText = "UPDATE Person SET forenames = #forenames WHERE " & _
" Reference = #Reference "
objCommand2.Parameters.AddWithValue("#forenames", i + 1)
objCommand2.Parameters.AddWithValue("#Reference", i)
objCommand2.ExecuteNonQuery()
objCommand2.Parameters.Clear()
End Using
trans.Complete()
End Using
Next
Catch ex As Exception
Throw
Finally
End Try
End Sub
This code works i.e. on each loop the changes are committed to the database.
Now please see the code below:
Private Sub TransactionExample3()
Dim objDR As SqlDataReader
Dim objCommand As SqlCommand, objCommand2 As SqlCommand
Dim objCon As SqlConnection
Dim objCon2 As SqlConnection
Dim id As Integer
Try
_ConString = "Data Source=server;Initial Catalog=Person;User ID=Username;Password=Password;MultipleActiveResultSets=True"
objCon = New SqlConnection(_ConString)
objCommand = New SqlCommand("SELECT top 10 * from Person")
objCommand.Connection = objCon
objCon.Open()
objDR = objCommand.ExecuteReader()
Do While objDR.Read
objCon2 = New SqlConnection(_ConString)
objCon2.Open()
Using trans = New TransactionScope()
objCommand2 = New SqlCommand()
objCommand2.Connection = objCon
Using objCon2
objCommand2.CommandText = "UPDATE Person SET forenames = #forenames WHERE " & _
" Reference = #Reference "
objCommand2.Parameters.AddWithValue("#forenames", objDR("Reference") + 10)
objCommand2.Parameters.AddWithValue("#Reference", objDR("Reference"))
objCommand2.ExecuteNonQuery()
objCommand2.Parameters.Clear()
End Using
End Using
Loop
objDR.Close() 'line 16
Catch ex As Exception
Throw
Finally
End Try
End Sub
In the second code exherpt, the scope is not complete (scope.complete), however the results are still committed to the database on each iteration of the while loop. Why is this?
In the first loop the opening of the TransactionScope is before the opening of the connection. In the second one is after. The connection is not enlisted in the Transaction and thus every command executes without being held by a transaction.
Try to switch these lines
Do While objDR.Read
Using trans = New TransactionScope()
objCon2 = New SqlConnection(_ConString)
objCon2.Open()
.....
Now you need the call to trans.Complete()
Private Sub TransactionExample3()
Dim objDR As SqlDataReader
Dim objCommand As SqlCommand, objCommand2 As SqlCommand
Dim objCon As SqlConnection
Dim objCon2 As SqlConnection
Dim id As Integer
_ConString = "Data Source=server;Initial Catalog=Person;User ID=Username;Password=Password;MultipleActiveResultSets=True"
Using objCon = New SqlConnection(_ConString)
objCommand = New SqlCommand("SELECT top 10 * from Person")
objCommand.Connection = objCon
objCon.Open()
objDR = objCommand.ExecuteReader()
Using trans = New TransactionScope()
Using objCon2 = New SqlConnection(_ConString)
objCon2.Open()
Do While objDR.Read
objCommand2 = New SqlCommand()
objCommand2.Connection = objCon
Using objCon2
objCommand2.CommandText = "UPDATE Person SET forenames = #forenames WHERE " & _
" Reference = #Reference "
objCommand2.Parameters.AddWithValue("#forenames", objDR("Reference") + 10)
objCommand2.Parameters.AddWithValue("#Reference", objDR("Reference"))
objCommand2.ExecuteNonQuery()
objCommand2.Parameters.Clear()
End Using
Loop
objDR.Close() 'line 16
End Using
trans.Complete()
End Using
End Using
End Sub
I suggest to move the Transaction and Connection opening outside the loop and call the Complete and destroy the connection after the foreach loop, if I understand your code correctly you update one record at each loop and so the Transaction makes sense only if you want to update all of your records or none. Another minor optimization could be to move the creation of the SqlCommand and the Parameters outside the loop. You update just the parameters value inside the loop without destroying and rebuilding the parameter collection at each loop

How can I change this code to SqlConnection?

Can anyone change this code to SqlConnection?
Dim Db As ADODB.Connection
Dim rs As ADODB.Recordset
Set Db = New ADODB.Connection
Db.ConnectionString = GetConnectString & AppPath & "schedule.mdb"
Call Db.Open
Set rs = New ADODB.Recordset
Set rs = Db.Execute("select * from tbl_Schedule where StartDate = #1/1/2002#")
While Not rs.EOF
Call Me.Schedule1.ScheduleItems.Add("", #1/1/2002#, rs!StartTime, _
rs!Length, rs!Description, "")
Call rs.MoveNext
Wend
Please find the below snippet which will helps you to get data from sql database. You can alter the script with your values. Import System.Data.SqlClient namespace to work with SqlConnection
Dim connection As New SqlConnection("Server=.\sqlexpress;Integrated security=sspi;database=Automation")
Dim query As String = "Select * from Heads"
If connection.State = ConnectionState.Closed Then connection.Open()
Using cmd As New SqlCommand(query, connection)
Dim reader As SqlDataReader = cmd.ExecuteReader
While reader.Read
ListBox1.Items.Add(reader("HeadName").ToString)
End While
reader.Close()
connection.Close()
End Using