I am using the following SQL statement :
Dim strSql5 As String = "SELECT * FROM dbo.ontledings " & _
" where plaasblok = #plaasblokparsversoeke " & _
" and analisedatum = #laastedatum"
cnn.Open()
Dim aksie2 As New SqlClient.SqlCommand(strSql5, cnn)
aksie2.Parameters.Add("#plaasblokparsversoeke", SqlDbType.VarChar).Value = plaasblokparsversoeke
aksie2.Parameters.Add("#laastedatum", SqlDbType.Date).Value = laastedatum
aksie2.ExecuteNonQuery()
cnn.Close()
I want to fill a datatable like so :
Dim dtb5 As New DataTable
dtb5.Clear()
Using cnn As New SqlConnection("Data Source=GIDEON-E-LAPTOP\SQLEXPRESS2014;Initial Catalog=SkeduleringDatabasis;Integrated Security=True")
cnn.Open()
Using dad5 As New SqlDataAdapter(strSql5, cnn)
dad5.Fill(dtb5)
End Using
cnn.Close()
End Using
I get the following error message : Must declare the scalar variable "#plaasblokparsversoeke"
I cannot figure out where and how to declare the scalar variables.
The error occurs at the line : dad5.Fill(dtb5)
Regards
You need to add the parameters like
cmd.Parameters.Clear()
cmd.Parameters.AddWithValue("#plaasblokparsversoeke", plaasblokparsversoeke.Text)
cmd.Parameters.AddWithValue("#laastedatum", laastedatum.Text)
As correctly commented below, you need to use the Add method to add the paramters:
cmd.Parameters.Add("#plaasblokparsversoeke", SqlDbType.Varchar).Value = plaasblokparsversoekeVariable;
cmd.Parameters.Add("#laastedatum", SqlDbType.Varchar).Value = laastedatumVariable;
Firstly, avoid hard-coding a parameterised query in this way, for avoidance of SQL injection.
To answer your specific question: you are trying to use parameters in the query without having defined them in the SQLCommand.
Have a look at MSDN for the full documentation.
With this query
Dim strSql5 As String = "SELECT * FROM dbo.ontledings " & _
" where plaasblok = #plaasblokparsversoeke " & _
" and analisedatum = #laastedatum"
You are definining 2 SQL variables called #plaasblokparsversoeke and #laastedatum that you have to pass as parameters to your command, like this
command.Parameters.Add("#plaasblokparsversoeke", SqlDbType.Int);
command.Parameters["#plaasblokparsversoeke "].Value = yourValue;
MSDN article on SQL command parameters here
Related
I write a sql statement into vb.net to fetch data from msaccess where date equal to patepicker control. But here syntax error.
My code given below:-
Dim ct As String = "select * from add_student where _Date <= #" & dtDate1.ToString("MM/dd/yyyy") & "#"
cmd = New OleDbCommand(ct)
cmd.Connection = con
rdr = cmd.ExecuteReader()
Note:- _Date column had Date/Time Data type in ms access database
Please suggest me, Where is mistake
You should always use parameters:
dim sqlQuery ="Select * from add_student where _Date = ?"
using conn = New OleDbConnection("connectionstring")
conn.open()
Using selectCmd As New OleDbCommand(sqlQuery, conn)
selectCmd.Parameters.Add("_Date", OleDbType.Date).Value = dtDate1
using rdr = selectCmd.ExecuteReader()
while rdr.read()
End While
End Using
End Using
End Using
Your issue may be that "/" is not a slash but the localized date separator.
Thus, force slashes:
Dim ct As String = "select * from add_student where _Date <= #" & dtDate1.ToString("MM'/'dd'/'yyyy") & "#"
and perhaps brackets for the weird field name:
Dim ct As String = "select * from add_student where [_Date] <= #" & dtDate1.ToString("MM'/'dd'/'yyyy") & "#"
I have some simple code that will load all the data from an excel sheet into an array but I am getting an error 94 inproper use of null due to the fact that my source sheet has some blank columns IE: Q through EA are blank columns but A -P and EB - EF have data. (terrible design for an excel sheet being used as a table I know,.. but I didn't do it)
Seeing as I cant redesign the table.. how can I skip the blanks as to avoid causing errors when loading them into my array?
Dim Conn As New ADODB.Connection
Dim mrs As New ADODB.Recordset
Dim DBPath As String, sconnect As String
DBPath = "\\MYPATH\MYFILE.xlsm"
sconnect = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & DBPath _
& ";Extended Properties=""Excel 12.0;HDR=Yes;IMEX=1"";"
Conn.Open sconnect
sSQLSting = "SELECT * From [log$]"
mrs.Open sSQLSting, Conn
'=>Load the Data into an array
ReturnArray = mrs.GetRows
'Close Recordset
mrs.Close
'Close Connection
Conn.Close
The IsNull() function returns True or False. So include it inside Jet/ACE's conditional logic function IIF()
sSQLString = "SELECT IIF(IsNull(Col1), 0, Col1)," _
& " IIF(IsNull(Col2), 0, Col2)," _
& " IIF(IsNull(Col3), 0, Col3)"
& " From [log$];"
#JohnsonJason Why do you need it in a Array? You could just filter your data with Advanced Filter like here or just drop it and loop to get the columns you need. If you don't know how many columns will be you can create a clone Recordset and get the columns Name and create your Query based on that.
The clone RecordSet is something like this:
'' Declare Variables
Dim oRst As ADODB.Recordset, oRstVal As ADODB.Recordset, oStrm As ADODB.Stream
Dim sHeaders as String
'' Set Variables
Set oRst = New ADODB.Recordset
Set oRstVal = New ADODB.Recordset
Set oStrm = New ADODB.Stream
.... [Something else]
'' Save your current Recordset in the Stream
oRst.Save oStrm
'' Assign your Stream to the new Recordset (oRstVal)
oRstVal.Open oStrm
'' Loop trough your Recorset for Columns Name
'' Use an IF or a Select to filter
For iCol = 0 To oRstVal.Fields.Count - 1
sHeaders = sHeaders + "," + oRstVal.Fields(iCol).Name
Next
And use sHeaders in your Statement in to get the columns you need.
''Instead of Select * From ...
sQuery = "Select " + sHeaders + _
"From ...."
Is there a way to use DateTimePicker as your searching device for ListView?
I don't know how to use DateTimePicker as my search engine...
HERE IS THE CODES FOR MY SEARCH:
Dim conn As SqlConnection
Dim cmd As SqlCommand
Dim da As SqlDataAdapter
Dim ds As DataSet
Dim itemcoll(100) As String
Me.ListView1.View = View.Details
Me.ListView1.GridLines = True
ListView1.Items.Clear()
conn = New SqlConnection("Data Source=#####;Initial Catalog=#####;Persist Security Info=True;User ID=#####;Password=#####")
Dim strQ As String = String.Empty
strQ = "SELECT ControlNo,EmpNo,CheckOutDate,CheckOutTime,TaxiNo,PlateNo,Model,Make FROM dbo.ChkInOut WHERE ControlNo ='" + txtsearch.Text + "'"
cmd = New SqlCommand(strQ, conn)
da = New SqlDataAdapter(cmd)
ds = New DataSet
da.Fill(ds, "Table")
Dim i As Integer = 0
Dim j As Integer = 0
For i = 0 To ds.Tables(0).Rows.Count - 1
For j = 0 To ds.Tables(0).Columns.Count - 1
itemcoll(j) = ds.Tables(0).Rows(i)(j).ToString()
Next
Dim lvi As New ListViewItem(itemcoll)
Me.ListView1.Items.Add(lvi)
Next
There are few problems with your code as is, so let's take them one at a time
SqlCommand inherits from DbCommand, which implements the IDisposable interface.
The primary use of this interface is to release unmanaged resources.
The best way do that is with the Using keyword. For a code example of that, take a look at the sample code at the bottom of this page.
Same goes for SqlConnection, wrap it in a Using statement.
Don't concatenate strings together to make SQL queries, this opens your application up to SQL Injection attacks. There are examples of how to create parameterized queries here and here (unfortunately I didn't see a good example on MSDN).
In your case, the query will look like this:
strQ = "SELECT ControlNo, ..<rest of columns>.. ,Model,Make " & _
"FROM dbo.ChkInOut " & _
"WHERE ControlNo = #controlNo"
cmd = New SqlCommand(strQ, conn)
cmd.Parameters.AddWidthValue("#controlNo", txtsearch.Text);
... rest of code here ...
To query by a user specified date, you need to first get the date from the DateTimePicker.Value property. Then construct a query (like in the example above) and pass a parameter with the selected date. You may find this question abou SQL Server dates helpful.
I'm new to the SQL query language and I'm trying to figure out how to delete a row (in a SQL DB table) with a non key ID column value using vb.net. For example in the table TEST below:
ID Name
1 x
2 y
3 z
I have a windows form that the user selects the Name value, however when I run my code it says
Cannot convert varchar "y" to int.
Here is my code attempt:
Dim sConnectionString As String
sConnectionString = "Data Source=" + serverName + ";Initial Catalog=" + dbName + ";Integrated Security=SSPI;"
Dim objConn As New SqlConnection(sConnectionString)
objConn.Open()
Dim cmd As New SqlCommand
cmd.Connection = objConn
cmd.CommandText = "DELETE FROM TEST WHERE Name = y"
cmd.ExecuteNonQuery()
Thank you!
If your Name column is of type varchar you need to enclose the value in single quotes
cmd.CommandText = "DELETE FROM TEST WHERE Name = 'y'"
A complete answer to your question will be:
Dim sConnectionString As String
sConnectionString = "Data Source=" + serverName + _
";Initial Catalog=" + dbName + _
";Integrated Security=SSPI;"
Dim objConn As SqlConnection
Using(objConn = new SqlConnection(sConnectionString)
objConn.Open()
Dim cmd As New SqlCommand
cmd.Connection = objConn
cmd.CommandText = "DELETE FROM TEST WHERE Name = #name"
cmd.Parameters.AddWithValue("#name", txtName.Text)
cmd.ExecuteNonQuery()
End Using
I'm supposing that your user insert the name to delete in a textbox and you pass this value to a parametrized query. The use of parametrized query will save you from the hassle to handle quoting problems and from Sql Injection Attacks
If you do this you will be deleting all rows WHERE Name = y and you probably don't want to do that.
You should use the name in the UI but pass the ID to SQL.
If you really do want to delete ALL rows with that name then put quotes around the y, as without them it's looking for a column named y:
DELETE FROM TEST WHERE Name = 'y'
cmd.CommandText = "DELETE FROM TEST WHERE Name = y";
instead you can use this one
cmd.CommandText = "DELETE FROM TEST WHERE ID = " + idValue;
here the 'idValue' is the ID that u take from the user
OR OTHER WISE
cmd.CommandText = "DELETE FROM TEST WHERE Name = 'y'";
I am reading data from an sql database and the connection happens but the following error occurs:
{"Index was outside the bounds of the array."}
On this line:
TextBox2.Text = TextBox2.Text & sqRdr.GetValue(22) & vbCrLf
Please help me with this as I have counted all the columns in my table and they have turned out to be exactly (22).
The column ordinal for the datareader is 0 based, so the 22nd column would be sqRdr.GetValue(21)
Your Datareader should be like below to avoid this issue in a case when you have increased/decreased the number of column in future....
DR["ColumnName"]
SqlDataReader's this[string name] looks like:
Public Overrides Default ReadOnly Property Item(name As String) As Object
Get
Return Me.GetValue(Me.GetOrdinal(name))
End Get
End Property
Below is the sample code...
Using con As System.Data.SqlClient.SqlConnection = New SqlConnection("YourConnection string")
con.Open()
Dim cmd As New SqlCommand()
Dim expression As String = "Parameter value"
cmd.CommandType = CommandType.StoredProcedure
cmd.CommandText = "Your Stored Procedure"
cmd.Parameters.Add("Your Parameter Name", SqlDbType.VarChar).Value = expression
cmd.Connection = con
Using dr As IDataReader = cmd.ExecuteReader()
'You code like ....dr["YourColumnName"]
If dr.Read() Then
End If
End Using
End Using