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

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.

Related

How to execute query and store data of a column in a variable in VB.net?

I have the following code where I am trying to execute a query and store the value from the database in two variables. Depending on the variables, I would like to tick a checkbox and add some text to a textbox.
Here is the code:
Try
Dim cn As SqlConnection
Dim strCnn As String = ConfigurationManager.ConnectionStrings("agilityconnectionstring").ConnectionString
cn = New SqlConnection(strCnn)
cn.Open()
Dim comm As New SqlCommand("select IsCompleted, CompletionDate from managerchecklist where ID = 53 and QuestionID = 1", cn)
comm.CommandType = CommandType.Text
Dim ds As SqlDataReader
ds = comm.ExecuteReader()
If ds.HasRows Then
While ds.Read
IsComplete = ds.Item("IsCompleted").ToString()
CompleteDate = ds.Item("CompletionDate").ToString()
identifytasks_done.Checked = True
identifytasks_date.Attributes.Add("style", "display:block")
identifytasks_date.Text = CompleteDate
End While
End If
''Close your connections and commands.
cn.Close()
Catch ex As Exception
''Handle error if any
End Try
But I seem to be going wrong somewhere. Can anyone please help me?
Depending on the variables, I would like to tick a checkbox and add some text to a textbox.
Have an If Statement to check the variables whether it is complete
If IsComplete = "complete" Then
identifytasks_done.Checked = True
identifytasks_date.Attributes.Add("style", "display:block")
identifytasks_date.Text = CompleteDate
End If
Move the checking to SQL statement
Dim comm As New SqlCommand(
"select IsCompleted, CompletionDate from " +
"managerchecklist where ID = 53 and QuestionID = 1 and "
"IsCompleted = 'complete'",
cn)
Consider using parameter SQL instead to prevent SQL injection
I would recommend a Using statement for SQL queries and also parameters.
Get the values from SQL then use an IF statement to do whatever based on the values.
Assuming IsCompleted is a bit field in SQL....
Dim isCompleted As Boolean
Dim completedDate As Date
Using con As New SqlClient.SqlConnection(ConfigurationManager.ConnectionStrings("agilityconnectionstring").ConnectionString)
Using cmd As New SqlClient.SqlCommand("SELECT [IsCompleted], [CompletionDate] FROM managerchecklist where [ID] = #managerchecklistID and [QuestionID] = #questionID", con)
cmd.Parameters.Add("#managerchecklistID", SqlDbType.Int).Value = 53
cmd.Parameters.Add("#questionID", SqlDbType.Int).Value = 1
con.Open()
Using reader As SqlClient.SqlDataReader = cmd.ExecuteReader
While reader.Read
'Index in order of the columns in the SELECT statement
If reader.GetSqlBoolean(0).IsNull = False Then isCompleted = reader.GetSqlBoolean(0)
If reader.GetSqlDateTime(1).IsNull = False Then completedDate = reader.GetSqlDateTime(1)
End While
End Using
End Using
End Using
If isCompleted Then
identifytasks_done.Checked = True
identifytasks_date.Attributes.Add("style", "display:block")
identifytasks_date.Text = completedDate
End If
You could place this in a Sub of it's own with managerchecklistID and questionID as arguments then set the parameter values with the arguments
cmd.Parameters.Add("#managerchecklistID", SqlDbType.Int).Value = managerchecklistID
cmd.Parameters.Add("#questionID", SqlDbType.Int).Value = questionID

Must declare the scalar variable, but its declared

I've declared a variable in the code, but I'm clueless on how its still showing the error, any ideas?
When I remove the WHERE clauses after it shows every row, but when putting them in I get "Must declare the scalar variable #startdata".
connect()
cmd.CommandText = "SELECT h_initials, h_date, h_hours FROM [h_holidays] WHERE h_date >= #startdata AND h_date < #enddata "
cmd.Parameters.Clear()
cmd.Parameters.Add("#startdata", SqlDbType.DateTime).Value = datetime_date.Value
cmd.Parameters.Add("#enddata", SqlDbType.DateTime).Value = datetime_2.Value
cmd.ExecuteScalar()
Dim dataAdapter_holidays_all = New SqlDataAdapter(cmd.CommandText, con.ConnectionString)
Dim table_holidays_all As New DataTable()
table_holidays_all.Locale = System.Globalization.CultureInfo.InvariantCulture
dataAdapter_holidays_all.Fill(table_holidays_all)
Me.bs_holidays_all.DataSource = table_holidays_all
dgv_holidays_all.DataSource = bs_holidays_all
disconnect()
dgv_holidays_all.RowHeadersWidth = "28"
dgv_holidays_all.Columns(0).HeaderText = "User:"
dgv_holidays_all.Columns(1).HeaderText = "Date:"
dgv_holidays_all.Columns(2).HeaderText = "Hours:"
dgv_holidays_all.EnableHeadersVisualStyles = False
I've tried .addwithvalue on the parameters with still no luck.
No, it's not declared. Your code is rather all over the place. You first create a SqlCommand object, add parameters to it and call its ExecuteScalar method, but that makes no sense because you are retrieving more than one value. You then create a SqlDataAdapter with the same SQL but you don't add any parameters to its SelectCommand.
What you should be doing is creating a SqlDataAdapter, getting its SelectCommand and adding the parameters to it, e.g.
Dim sql = "SELECT h_initials, h_date, h_hours FROM [h_holidays] WHERE h_date >= #startdata AND h_date < #enddata"
Dim adapter As New SqlDataAdapter(sql, con)
With adapter.SelectCommand.Parameters
.Add("#startdata", SqlDbType.DateTime).Value = datetime_date.Value
.Add("#enddata", SqlDbType.DateTime).Value = datetime_2.Value
End With
No additional SqlCommand object. No pointless call to ExecuteScalar.

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

select records between two date in vb.net gives error operand type clash

i need to select some records from table Tr_cashbook between two date. the date field is newdt in which i need to compare data and the records should be shown in crystal report named rptCash2. the newdt field has datetime property. here is the code on the command button
bdcon.Open()
Dim QueryString As String
QueryString = "Select * from Tr_Cashbook where (Cast(newdt as date)>= " & DateTimePicker1.Value.ToString("yyyy-MM-dd") & ") and (Cast(newdt as date) <= " & DateTimePicker2.Value.ToString("yyyy-MM-dd") & ")"
Dim Adapter As SqlDataAdapter = New SqlDataAdapter(QueryString, bdcon)
Dim ds As DataSet = New DataSet()
Adapter.Fill(ds, "Tr_Cashbook")
rptCash2.Load()
rptCash2.SetDataSource(ds)
CrystalReportViewer1.ReportSource = rptCash2
bdcon.Close()
but this is not working
when i press the command button it gives error as operand type clash: date is incompatible with int. i am not able to find out where i go wrong . help me with this..
Use parameters instead of hard-coded sql string.
Your parameterized query shoud be:
QueryString = "Select * from Tr_Cashbook where newdt>=#date1 and
newdt<= #date2"
Dim Cmd as new SqlCommand(QueryString,bdcon)
Cmd.Parameters.Add("#date1",SqlDbType.Date).Value=DateTimePicker1.Value
Cmd.Parameters.Add("#date2",SqlDbType.Date).Value=DateTimePicker2.Value
Dim Adapter As SqlDataAdapter = New SqlDataAdapter(Cmd)
Dim ds As DataSet = New DataSet()
Adapter.Fill(ds, "Tr_Cashbook")
You may use BETWEEN AND syntax:
QueryString = "Select * from Tr_Cashbook where newdate BETWEEN #date1 AND #date2"