SQL read data from table in vb - sql

I'm trying to get a single field back from the data. (I am searching by a primary key so I should get 0 or 1 answer). Please help. The table that I am querying has one entry with user = someone, input to several columns with the ans column having "a good answer"
Code:
Dim reader As SqlDataReader
Dim par As SqlParameter
Dim result As String
Dim sqlconn As SqlConnection
sqlconn = New SqlConnection("....")
sqlconn.Open()
Dim sqlcmd As SqlCommand
sqlcmd = New SqlCommand("Select Ans From Test Where User = #auser", sqlconn)
par = New SqlParameter
par.ParameterName = "auser"
par.Value = Textbox1.Text
sqlcmd.Parameters.Add(par)
reader = sqlcmd.ExecuteReader()
result = reader.GetString(0)
''//output to label
label1.Text = result

You need to read the data reader first to place it on the first row.
So instead of
reader = sqlcmd.ExecuteReader()
result = reader.GetString(0)
You'd insert the Read() method like so:
reader = sqlcmd.ExecuteReader()
if reader.Read() then '' <<<<< newly inserted code
result = reader.GetString(0)
end if

''// using statement will guarantee the object is closed and disposed
''// even if an exception occurs
Using sqlconn As New SqlConnection("...."), _
sqlcmd As New SqlCommand("Select Ans From Test Where User = #auser", sqlconn)
''// you can create, add, and set the value for a parameter all on one line
sqlcmd.Parameters.Add("#auser", SqlDbType.VarChar, 50).Value = Textbox1.Text
''//wait as long as possible to open the connection
sqlconn.Open()
''// if you're only getting the first column of the first row, use execute scalar
label1.Text = CString(sqlcmd.ExecuteScalar())
End Using

Related

How can I read a specific column in a database?

I hava a Table named DTR_Table it has 8 columns in it namely:
EmployeeID,Date,MorningTime-In,MorningTime-Out,AfternoonTime-In,AfternoonTime-Out,UnderTime,Time-Rendered.I want to read the column "AfternoonTime-In".
Following is my code. It reads my "AfternoonTime-In" field, but it keeps on displaying "Has Rows" even if there is nothing in that column.
How can I fix this?
Connect = New SqlConnection(ConnectionString)
Connect.Open()
Dim Query1 As String = "Select [AfternoonTime-Out] From Table_DTR Where Date = #Date and EmployeeID = #EmpID "
Dim cmd1 As SqlCommand = New SqlCommand(Query1, Connect)
cmd1.Parameters.AddWithValue("#Date", DTRform.datetoday.Text)
cmd1.Parameters.AddWithValue("#EmpID", DTRform.DTRempID.Text)
Using Reader As SqlDataReader = cmd1.ExecuteReader()
If Reader.HasRows Then
MsgBox("Has rows")
Reader.Close()
Else
MsgBox("empty")
End If
End Using`
After returning the DataReader you need to start reading from it if you want to extract values from your query.
Dim dt = Convert.ToDateTime(DTRform.datetoday.Text)
Dim id = Convert.ToInt32(DTRform.DTRempID.Text)
Using Connect = New SqlConnection(ConnectionString)
Connect.Open()
Dim Query1 As String = "Select [AfternoonTime-Out] From Table_DTR
Where Date = #Date and EmployeeID = #EmpID"
Dim cmd1 As SqlCommand = New SqlCommand(Query1, Connect)
cmd1.Parameters.Add("#Date", SqlDbType.DateTime).Value = dt
cmd1.Parameters.Add("#EmpID", SqlDbType.Int).Value = id
Using Reader As SqlDataReader = cmd1.ExecuteReader()
While Reader.Read()
MessageBox.Show(Reader("AfternoonTime-Out").ToString())
Loop
End Using
End Using
Note that I have changed the AddWithValue with a more precise Add specifying the parameter type. Otherwise, your code will be in the hand of whatever conversion rules the database engine decides to use to transform the string passed to AddWithValue to a DateTime.
It is quite common for this conversion to produce invalid values especially with dates

VB: SQL Query return result to textbox

In short, I am working on a program that will add/edit entries to an SQL database.
One of the features for this program is that it, if given the account ID number, will look up the name under that account with that given ID. This is what I am having trouble with.
General Format:
Objective: SQL Query that will return string to textbox
AcctID => field in table with account number
AcctName => field in table with account name
txtbx_accountName => textbox I need the name returned to
NOTE:
This is all nested in a generic Try-Catch statement with error
handling.
This is all inside a Click event handler for a button.
This is all done in Visual Studio 2015
Dim myConn As New SqlConnection
Dim myCmd As New SqlCommand
myConn.ConnectionString = ""
myConn.Open() ' Open the connection
myCmd = myConn.CreateCommand()
' Build the query with the account number as paramter
myCmd.CommandText = "SELECT AcctName FROM DataSetTable WHERE (AcctID = #incomingAcctID)"
' Add the parameter so the SqlCommand can build the final query
myCmd.Parameters.Add(New SqlParameter("#incomingAcctID", (CInt(txtbx_accountNum.Text))))
' run the query and obtain a reader to get the results
Dim reader As SqlDataReader = myCmd.ExecuteReader()
' check if there are results
If (reader.Read()) Then
' populate the values of the controls
txtbx_accountName.Text = reader(0)
End If
' Close all connections
myCmd.Dispose()
myConn.Close() ' Close connection
myConn.Dispose()
i am not pro but i do like this,sorry if this not helped you:
if your Stored procedure is created to add and edit than write this and call it where you want to add:
private sub NAME(ByVAL Parameter1 name as integer,
ByVAL Parameter2 name as string,
ByVAL Parameter3 name as boolean)
Dim strConn As String = ConfigurationManager.ConnectionStrings("databaseXYZ").ConnectionString
Dim myConn As New SqlConnection(strConn)
Dim myCmd As SqlCommand
try
myConn.Open()
sqlCommand = New SqlCommand("PRCEDURE_NAME", myConn )
sqlCommand.CommandType = CommandType.StoredProcedure
dim param as new System.Data.SqlClient.SqlParameter
param.parameterName="#send_parameter1"
param.Direction = ParameterDirection.Input
param.Value = send_parameter1
dim param1 as new System.Data.SqlClient.SqlParameter
param1.parameterName="#send_parameter2"
param1.Direction = ParameterDirection.Input
param1.Value = send_parameter2
sqlCommand.Parameters.Add(Param)
sqlCommand.Parameters.Add(Param1)
sqlCommand.ExecuteNonQuery()
catch ex as exception
throw
End Try
myConn.Close()
myConn = Nothing
end sub
I'm a dummy!!!
Here is the solution, for all interested parties.
Click Event Handler (w/ nested Try-Catch):
txtbx_accountName.Text = DataSetTableAdapter.SearchNameQuery(CInt(txtbx_accountNum.Text)).ToString
SearchNameQuery:
SELECT AcctName FROM DataSetTable WHERE AcctID = #incomingAcctID
More notes on this:
- The dataset is already included in the project

Populate ListBox from SQL only items with condition (first character)

I've managed to put all items in a ListBox, also have the first character defined kto, how to insert only those values from List column into Listbox that begin with that character kto.
Just to mention that kto is value from 0 to 9, always a number.
Dim SqlSb As New SqlConnectionStringBuilder()
SqlSb.DataSource = ".\sqlexpress"
SqlSb.InitialCatalog = "Konta"
SqlSb.IntegratedSecurity = True
Using SqlConn As SqlConnection = New SqlConnection(SqlSb.ConnectionString)
SqlConn.Open()
Dim cmd As SqlCommand = SqlConn.CreateCommand()
cmd.CommandText = "SELECT List FROM Konta"
Dim kto = Left(Label1.Text, 1)
'Label3.Text = kto
Using reader As SqlDataReader = cmd.ExecuteReader
While (reader.Read())
Me.ListBox1.Items.Add(reader("LIST"))
End While
End Using
SqlConn.Close()
End Using
Try this
Dim SqlSb As New SqlConnectionStringBuilder()
SqlSb.DataSource = ".\sqlexpress"
SqlSb.InitialCatalog = "Konta"
SqlSb.IntegratedSecurity = True
Using SqlConn As SqlConnection = New SqlConnection(SqlSb.ConnectionString)
SqlConn.Open()
Dim cmd As SqlCommand = SqlConn.CreateCommand()
Dim kto = Left(Label1.Text, 1)
cmd.CommandText = "SELECT List FROM Konta WHERE List LIKE '" & kto.toString & "%'"
ListBox1.Items.Clear
Using reader As SqlDataReader = cmd.ExecuteReader
While (reader.Read())
Me.ListBox1.Items.Add(reader("LIST"))
End While
End Using
SqlConn.Close()
End Using
In your while loop, before adding the item in the listbox check the date type of reader("LIST") and add it only if matches the required type.
You can check the type using the following code:
reader.GetFieldType(0)

Update Access database records by column, row known

This is what I've got so far :
Dim myCONN As OleDbConnection = New OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=w:\Baza.mdb")
Dim cmd1 = New OleDbCommand("SELECT ID FROM Baza WHERE NAZIV=#XXNAZIV")
cmd1.Parameters.AddWithValue("#XXNAZIV", TextBox2.Text)
cmd1.Connection = myCONN
myCONN.Open()
Dim result = cmd1.ExecuteReader()
While (result.Read())
Dim rowx As Integer = GetTextOrEmpty(result("ID"))
End While
I've found the row (rowx) in which I would like to change values in 20 corresponding columns (namesID : NAZIV, SIFRA,...). Data is already presented in textboxes (textbox1...), but I don't know how to finish this code with UPDATE and how to insert changed values back to Access.
Dim cmdText As String = "UPDATE Baza SET NAZIV=#XXNAZIV Where ID=SomeId"
Using con = new OleDbConnection("PROVIDER=Microsoft.ACE.OLEDB.12.0;Data Source = h:\Baza.mdb")
Using cmd = new OleDbCommand(cmdText, con)
con.Open()
cmd.Parameters.AddWithValue("#XXNAZIV",TextBox2.Text)
cmd.ExecuteNonQuery()
End Using
End Using
This should help you to solve your problem, of course you will have to pass ID parameter to query also.
Reference

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()