How can I read a specific column in a database? - vb.net

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

Related

How to populate a combobox from two different SQL Server database tables

I am trying to create a system that will load items from a database. There are two comboboxes; combobox1 which loads items from database table 1 and combox2 which loads items from database table 2.
Both tables are in the same database.
Here is was I tried but when I run the system I get this error:
(Conversion from string "SELECT * FROM dbo.Dishes" to type 'Long' is not valid.)
Here is the code I'm using:
Dim connection As New SqlConnection("Server = DESKTOP-1373H91; Initial Catalog = MealPreOrderSystem; Integrated Security = True")
connection.Open()
Dim query As String = "SELECT * FROM dbo.Dishes" And "SELECT * FROM dbo.Desserts"
Dim cmd As SqlCommand
cmd = New SqlCommand(query, connection)
Dim reader As SqlDataReader
reader = cmd.ExecuteReader
While reader.Read
cbxType.Items.Add(reader.Item("MealName"))
cbxType.Items.Add(reader.Item("DessertName"))
End While
connection.Close()
In VB.NET,AND is an operator.It is used to perform conjunction between either Booleans or Integers/Doubles/any numeric expression.Lets take your query string as an example :
Dim query As String = "SELECT * FROM dbo.Dishes" And "SELECT * FROM dbo.Desserts"
You are using AND here to join 2 sentences/strings which wouldn't result in anything rather it is trying to cast it as a Long.
Try to execute this command in SQL and you won't find any luck :(.
Your statements are correct :
SELECT * FROM dbo.Dishes
SELECT * FROM dbo.Desserts
But the way you are trying to achieve your goals is incorrect :(.
To get the data from the database into your combobox, what you can do is either use two comboboxes with separated SQL Queries/SQL Commands or you can use one combobox where you add data from both the databases but separate them with some special characters such as a comma ,
A sample may look like :
With one combobox
Dim cmd1 as new SqlCommand("SELECT * FROM dbo.Dishes",connection)
Dim dr as SqlDatareader = cmd1.ExecuteReader
While dr.Read
mycombo1.Items.Add(dr(0)) ' Here 0 is the column count,change it as required
End while
Dim cmd2 as new SqlCommand("SELECT * FROM dbo.Desserts",connection)
Dim dr2 as SqlDatareader = cmd2.ExecuteReader
While dr2.Read
mycombo2.Items.Add(dr2(0)) ' Here 0 is the column count,change it as required
End while
With 1 combobox
Here it gets a bit complicated.Firstly you need to populate your combobox from the data received from the first dataReader.Then, when the 2nd datareader is reading the data , you need to update the existing data/Item of the combobox keeping the existing data/item but adding new data/item to each existing data/item(separating them with ,).
Sample :
Dim i as Integer
Dim cmd1 as new SqlCommand("SELECT * FROM dbo.Dishes",connection)
Dim dr as SqlDatareader = cmd1.ExecuteReader
While dr.Read
mycombo1.Items.Add(dr(0))
End while
Dim cmd2 as new SqlCommand("SELECT * FROM dbo.Desserts",connection)
Dim dr2 as SqlDatareader = cmd2.ExecuteReader
While dr2.Read
mycombo1.Items(i) = myconbo1.Items(i) & "," & dr2(0)
i = i + 1
End while
Now, NOTE THAT I AM USING MULTIPLE DATAREADERS WITH THE SAME CONNECTION ,SO YOU MAY NEED TO INCLUDE MultipleActiveResultSets=True IN YOUR CONNECTION STRING or ENCLOSE THE DATAREADERS IN USING STATEMENTS or CALL dataReader.Close AFTER EACH DATAREADER HAS COMPLETED READING FROM THE DATABASE
This will solve your issue :)
Looks like you don't know how to write SQL queries (and your VB syntax itself looks faulty - string AND string?).
Dim connection As New SqlConnection("Server = DESKTOP-1373H91; Initial Catalog = MealPreOrderSystem; Integrated Security = True")
Dim query As String = <cmdString>
SELECT MealName as Name FROM dbo.Dishes
union
SELECT DessertName as Name FROM dbo.Desserts
</cmdString>
Dim cmd As SqlCommand
Dim reader As SqlDataReader
connection.Open()
cmd = New SqlCommand(query, connection)
reader = cmd.ExecuteReader
While reader.Read
cbxType.Items.Add(reader.Item("Name"))
End While
connection.Close()
Note: You are saying 2 comboboxes but your code seemed to be loading all the items to a single combobox. If you really need 2 comboboxes then use 2 SqlCommand and Reader loops (actually it would be better if you simply have used Linq for this).
You should be a bit more specific on what columns you are pulling from the 2 tables. if they are similar, you could write a sql query to UNION ALL the fields with a simple control to identify which record came from which table.
Example of SQL command string:
"SELECT 'M' AS Ctl, MealName AS aName FROM dbo.Dishes " &
"UNION ALL " &
"SELECT 'D' AS Ctl, DessertName AS aName FROM dbo.Desserts"
As mentioned by many here already, it seems like you are referencing only 1 ControlBox to list the fields returned cbxType
below is the reader (adapted to 2 ComboBoxes):
While reader.Read
Select Case reader.Item("Ctl")
Case "M"
cbxMType.Items.Add(reader.Item("aName"))
Case "D"
cbxDType.Items.Add(reader.Item("aName"))
End Select
End While
Hope this helps

vb.net SQL causing - "Must declare the scalar variable "

I've been stuck on this error for a while, in vb.net trying to connect to SQL and pull data from a table within a day, using parameters to do this, a datetimepicker - the data saved to SQL is in a custom datetime format dd/MM/yyyy HH:mm:ss,
When i execute my code i get
"Must declare the scalar variable "#line"
When i remove the code " WHERE [line] = #line and date >= #startdata AND date < #enddata " it works but shows all the data without the date range as it should.
connect()
DataGridView1.AutoGenerateColumns = True
cmd.Parameters.Clear()
cmd.CommandText = #"SELECT board, defect, date, detail_x, detail_y,
detail_width, detail_height
FROM [sqlccmdefects]
WHERE [line] = #line
and date >= #startdata
AND date < #enddata";
cmd.Parameters.Add("#line", SqlDbType.VarChar, 30).Value = Form1.line.Text
cmd.Parameters.Add("#startdata", SqlDbType.DateTime).Value = DateTimePicker1.Value
cmd.Parameters.Add("#enddata", SqlDbType.DateTime).Value = DateTimePicker2.Value
cmd.ExecuteScalar()
Dim dataAdapter1 = New SqlDataAdapter(cmd.CommandText, con.ConnectionString)
Dim table1 As New DataTable()
table1.Locale = System.Globalization.CultureInfo.InvariantCulture
dataAdapter1.Fill(table1)
Me.BindingSource1.DataSource = table1
DataGridView1.DataSource = BindingSource1
disconnect()
All i get is a blank Datagridview with the scalar error.
There looks to be a couple of issues in the code you posted,
Try this:
'SQL Connection
Dim sqlCon As New SqlConnection("Server=.;Database=dummy;Trusted_Connection=True;")
'SQL Command
Dim sqlCmd As New SqlCommand("", sqlCon)
sqlCmd.CommandText = "SELECT board, defect, date, detail_x, detail_y, detail_width, detail_height FROM [sqlccmdefects] WHERE [line] = #line and date >= #startdata AND date < #enddata"
'SQL Command Params
sqlCmd.Parameters.Add("#line", SqlDbType.VarChar, 30).Value = "WHATEVER"
sqlCmd.Parameters.Add("#startdata", SqlDbType.DateTime).Value = "2015-07-21"
sqlCmd.Parameters.Add("#enddata", SqlDbType.DateTime).Value = "2015-07-23"
'Data Adapters
Dim dataAdapter1 = New SqlDataAdapter(sqlCmd)
Dim table1 As New DataTable()
'NOT SURE WHAT THIS DOES?
table1.Locale = System.Globalization.CultureInfo.InvariantCulture
'Attach to the GV
dataAdapter1.Fill(table1)
DataGridView1.AutoGenerateColumns = True
BindingSource1.DataSource = table1
DataGridView1.DataSource = BindingSource1
ExecuteScalar is typically used when your query returns a single value. If it returns more, then the result is the first column of the first row.
Use cmd.ExecuteReader() or cmd.ExecuteNonQuery() instead of cmd.ExecuteScalar()
cmd.ExecuteScalar()
will execute the command – consuming the parameters – and throwing away any result (use ExecuteNonQuery when there is no result: saves setting up to return values).
When you fill the data adapter the command will be run again. But this time there are no parameters, and SQL fails on the first undefined identifier.
So: don't execute the command, instead pass the (unexecuted) command to the (single argument) data adapter constructor.

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

VB Count query result in a textbox

I want to populate the result of an SQL count query on a Access database in a textbox showing how many results there are. For example I have a code number inputted into the database 200 time, i want the textbox to show 200.
Heres my code so far:
ID = DataGridView1.CurrentRow.Cells(0).Value
fn = DataGridView1.CurrentRow.Cells(1).Value
ln = DataGridView1.CurrentRow.Cells(2).Value
SKU = DataGridView1.CurrentRow.Cells(4).Value
FC = DataGridView1.CurrentRow.Cells(5).Value
Dim countNoTwo As String = "SELECT COUNT skuNo FROM table WHERE skuNo = " & SKU & ""
Dim connection As New OleDbConnection(duraGadgetDB)
Dim dataadapter As New OleDbDataAdapter(countNoTwo, connection)
Dim ds As New DataSet()
connection.Open()
dataadapter.Fill(ds, "dura")
connection.Close()
txtbox1.Text
How do i bind the result of the dataset to the txtbox1.Text?
First, do not use string concatenation to build sql commands
(reason=Sql Injection + Parsing problems)
Second, if your command returns only one single result you could use
ExecuteScalar
Third, use the Using statement to be sure that your connection and
commands are correctly disposed after use
Dim countNoTwo As String = "SELECT COUNT skuNo FROM table WHERE skuNo = ?"
Using connection As New OleDbConnection(duraGadgetDB)
Using command As New OleDbCommand(countNoTwo, connection)
command.Parameters.AddWithValue("#sku", SKU)
connection.Open()
Dim result = Convert.ToInt32(command.ExecuteScalar())
txtbox1.Text = result.ToString
End Using
End Using
Try this
Dim dt As DataTable = ds.Tables(0)
txtbox1.Text = dt.Rows(0).Item(0).ToString()

SQL read data from table in vb

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