Is filling a DataTable necessary for just setting variables with 2 column values? - vb.net

I am trying to improve performance of an application, I have a case where a common SPROC is being used but is it necessary to fill a DataTable just to set 2 variable values?
Is there anything more efficient?
Dim Conn As SqlConnection = New SqlConnection(ConfigurationManager.ConnectionStrings("DB").ConnectionString)
Dim CmdUsers As SqlCommand = New SqlCommand("uspGetUsers", Conn)
CmdUsers.CommandType = CommandType.StoredProcedure
CmdUsers.Parameters.Add(New SqlParameter("#UserName", Session("UserID")))
Dim da As SqlDataAdapter = New SqlDataAdapter
Dim dtUserInfo As DataTable = New DataTable
da = New SqlDataAdapter(CmdUsers)
da.Fill(dtUserInfo)
isParent = dtUserInfo.Rows(0)("IsAdmin")
UserVal = dtUserInfo.Rows(0)("UserVal")

A SqlDataReader is the fastest way to read data from a query. Try the following:
Using conn As SqlConnection = New SqlConnection(ConfigurationManager.ConnectionStrings("DB").ConnectionString)
conn.Open()
Using cmd As New SqlCommand("uspGetUsers", conn)
cmd.CommandType = CommandType.StoredProcedure
cmd.Parameters.AddWithValue("#UserName", Session("UserID"))
Using reader As SqlDataReader = cmd.ExecuteReader()
While reader.Read()
isParent = reader("IsAdmin")
UserVal = reader("UserVal")
End While
End Using
End Using
End Using
You may need to parse the data to the correct types.
Also, note the use of Using to automatically dispose of the connection, command and reader objects: http://msdn.microsoft.com/en-GB/library/htd05whh.aspx

Related

Showing data in textbox

I am trying to get data from a database (which I have done and know that works)
However I want to push the data into a variable.
I can not see what is wrong, at the moment there is a mistake around "cmd.select" so if someone could point me in the right direction that would be great!
Dim cn As SqlConnection = New SqlConnection()
Dim cmd As SqlCommand = New SqlCommand()
Dim sqladp As New SqlDataAdapter()
Dim ds As New DataSet()
cmd.Parameters.Clear()
cn.ConnectionString = ConfigurationManager.ConnectionStrings("PemcoConnectionString").ConnectionString
cmd.Connection = cn
GridView2.Visible = True
cmd.Connection = cn
cmd.CommandText = "spUserResultsDetails"
cmd.CommandType = CommandType.StoredProcedure
Session.Item("ID") = (sender.SelectedValue.ToString)
cmd.Parameters.AddWithValue("#ID", Session.Item("ID"))
For Each datarow As Data.DataRowView In cmd.Select(DataSourceSelectArguments.Empty)
sEmailAddress = datarow("UserEmail")
Next
sqladp.SelectCommand = cmd
sqladp.Fill(ds)
There are many things that need improvement, this should work:
Using cn = New SqlConnection(ConfigurationManager.ConnectionStrings("PemcoConnectionString").ConnectionString))
Using da = New SqlDataAdapter("spUserResultsDetails", cn)
da.SelectCommand.CommandType=CommandType.StoredProcedure
da.SelectCommand.Parameters.AddWithValue("#ID", CInt(Session.Item("ID")))
Dim table = New Data.DataTable()
da.Fill(table)
GridView2.DataSource = table
GridView2.DataBind()
End Using
End Using
A summary:
use the using statement always to ensure that disposable objects are getting disposed (closed) even on error
use a SqldataAdapter if you want to fill a DataTable, you don't need to open/close it with fill, use it's SelectCommand property to get a reference to the SqlCommand
set the table as DataSource of your GridView and DataBind it
if you use AddWithValue you should cast the passed objects to the correct type, otherwise the correct type cannot be inferred

VB | Loading SQL Query into Combobox

I am trying to fill a combobox with a SQL Result
I think my problem is handling the data in the datatable form.
Dim sql As String
Dim sqlquery As String
Dim ConnectionString As String
ConnectionString = "Data Source=(local);Initial Catalog=Control;Persist Security Info=True;User ID=user;Password=pass"
sqlquery = "Select dbName from Databases"
Using connection As SqlConnection = New SqlConnection(ConnectionString)
connection.Open()
Using conn As SqlCommand = New SqlCommand(sqlquery, conn)
Dim rs As SqlDataReader = comm.ExecuteReader
Dim dt As DataTable = New DataTable
dt.Load(cmboxDatabaseName)
End Using 'comm
End Using 'conn
When I run the program I just stare at a sad empty combobox.
Almost right, but you need to Load the datatable using the DataReader.
Then assing the DataTable to the DataSource of the Combo
Using connection As SqlConnection = New SqlConnection(ConnectionString)
connection.Open()
Using comm As SqlCommand = New SqlCommand(sqlquery, connection)
Dim rs As SqlDataReader = comm.ExecuteReader
Dim dt As DataTable = New DataTable
dt.Load(rs)
' as an example set the ValueMember and DisplayMember'
' to two columns of the returned table'
cmboxDatabaseName.ValueMember = "IDCustomer"
cmboxDatabaseName.DisplayMember = "Name"
cmboxDatabaseName.DataSource = dt
End Using 'comm
End Using 'conn
Also you could set the combobox ValueMember property to the name of the column that you will use as key for future processing and the DisplayMember property to the column name that you want to display as text to choose from for your user
you can also do it as
Dim Con = New SqlConnection(_ConnectionString)
Dim cmdAs New SqlCommand
Dim dr As New SqlDataReader
Try
If Con.State = ConnectionState.Closed Then
Con.Open()
cmd.Connection = Con
cmd.CommandText = "Select field1, field2 from table"
dr = cmd.ExecuteReader()
' Fill a combo box with the datareader
Do While dr.Read = True
ComboBoxName.Items.Add(dr.GetString(0))
ComboBoxName.Items.Add(dr.GetString(1))
Loop
Con.Close()
End If
Catch ex As Exception
MsgBox(ex.Message)
End Try
Hope it works for you.

How to call a query from MS Access 2010 (.accdb) within VB.Net 2010?

I have this code that populates a datagridview with data from ms access:
Dim con As New OleDbConnection
Dim ds As New DataSet
Dim da As OleDb.OleDbDataAdapter
Dim Sql As String
Sql = "SELECT * FROM myTable WHERE case_no=?"
Try
con.ConnectionString = "PROVIDER=Microsoft.ACE.OLEDB.12.0;Data Source=Sample.accdb;Persist Security Info=True;Jet OLEDB:Database Password=dbadmin2010"
con.Open()
Dim cmd As OleDbCommand = New OleDbCommand(Sql, con)
da.SelectCommand = cmd
cmd.Parameters.AddWithValue("case_no", case_no)
Dim ds As DataSet = New DataSet
da.Fill(ds, "Case Info")
DataGridView1.DataSource = ds.Tables("Case Info")
Catch ex As Exception
MsgBox(ex.Message)
End Try
Now I had just finished creating a query from design view within MS Access itself, is there a way to call that query and retrieve the results to my datagridview?
Just use the query name and set the command type, for example, in addition to what you already have, you can use the following notes:
Try
con.ConnectionString = enter_connection_string_here
con.Open()
cmd.Connection = con
cmd.CommandType = CommandType.StoredProcedure
cmd.CommandText = "NameOfQuery"
da.SelectCommand = cmd
cmd.Parameters.AddWithValue("case_no", case_no)
da.Fill(ds, "Case Info")

Saving record with dataset

I want to save a record in the database using a dataset, but my data is not committing into my database.
My code can be viewed below:
Dim mydataset1 As New MyDataSet
Dim row As DataRow = mydataset1.Tables("testtable").NewRow()
With row
.Item("name") = "Segun Omotayo"
.Item("address") = "Abuja"
End With
mydataset1.Tables("testtable").Rows.Add(row)
Any help will be appreciated
A DataSet/DataTable is a offline/in-memory representation of your database. If you want to update the database, you need to use a DataAdapter.
For example (assuming you're using MS-Sql-Server):
Public Function UpdateDataSet(dataSet As DataSet) As Int32
Using con = New SqlConnection(My.Settings.SqlConnection)
Dim sql = "INSERT INTO TUser(Name,Address)VALUES(#Name,#Address)"
Using cmd = New SqlCommand(sql, con)
cmd.Parameters.Add(New SqlParameter("#Name", SqlDbType.VarChar))
cmd.Parameters.Add(New SqlParameter("#Address", SqlDbType.VarChar))
Using da = New SqlDataAdapter()
da.InsertCommand = cmd
con.Open()
Dim rowCount = da.Update(dataSet)
Return rowCount
End Using
End Using
End Using
End Function
I could be rusty here since its a long time since I wrote any VB.NET or used data adapters/datasets/datatables but I think if you decide to take that route you would need code like this:
Dim connection As New SqlConnection("#####YourConnectionString#####")
connection.Open()
Dim adapter As New SqlDataAdapter("SELECT * FROM testtable", connection)
' For the line below to work, you must have a primary key field in "testtable"
Dim builder As New SqlCommandBuilder(adapter)
Dim testtable As New DataTable("testtable")
adapter.Fill(testtable)
Dim row As DataRow = testtable.NewRow()
With row
.Item("name") = "Segun Omotayo"
.Item("address") = "Abuja"
End With
testtable.Rows.Add(row)
adapter.Update(testtable)
connection.Close()

Retrieving rows from a MS Access Database View using Vb.Net

I've managed to get the following code...
con.ConnectionString = My.Settings.dbConnection
Dim sqlCmd As System.Data.OleDb.OleDbCommand = New System.Data.OleDb.OleDbCommand()
con.Open()
sqlCmd.Connection = con
Dim schemaTable As DataTable
schemaTable = con.GetOleDbSchemaTable(System.Data.OleDb.OleDbSchemaGuid.Views, Nothing)
To retrieve a list of Views in my Access database, but now I want to retrieve the results based on a selected View.
Is there a correct method in doing this, or do I take the SQL Statement from the DataTable returned for each row?
Suppose you have Query1 (View) in your Access database (Database1.accdb file). The following code will output each row of the query to the console (for demo purposes):
Dim con As OleDbConnection = New OleDbConnection()
con.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Database1.accdb;Persist Security Info=False;"
Dim sqlCmd As OleDbCommand = New System.Data.OleDb.OleDbCommand()
sqlCmd.CommandType = CommandType.StoredProcedure
sqlCmd.CommandText = "Query1"
sqlCmd.Connection = con
con.Open()
Dim reader As OleDbDataReader
reader = sqlCmd.ExecuteReader()
If reader.HasRows Then
While reader.Read()
Console.WriteLine(reader("Column1")) 'output specific column
End While
End If
Console.ReadLine()
Hope this helps