The parameterized query expects the parameter which was not supplied - sql

I'm having a problem with my code:
Private Sub TextBox2_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TextBox2.TextChanged
list.Items.Clear()
cmd.CommandText = "SELECT * FROM borrow where (Department LIKE '%" & TextBox2.Text & "%')"
cmd.Connection = con
cmd.CommandType = CommandType.Text
con.Open()
rd = cmd.ExecuteReader()
If rd.HasRows = True Then
While rd.Read()
Dim listview As New ListViewItem
listview.Text = rd("ID").ToString
listview.SubItems.Add(rd("Department").ToString)
listview.SubItems.Add(rd("Purpose").ToString)
listview.SubItems.Add(rd("Items_Details").ToString)
listview.SubItems.Add(rd("Requested_by").ToString)
listview.SubItems.Add(rd("Approved_by").ToString)
listview.SubItems.Add(rd("Date").ToString)
listview.SubItems.Add(rd("Status").ToString)
listview.SubItems.Add(rd("Date_Returned").ToString)
list.Items.Add(listview)
End While
End If
con.Close()
Once I typed in the string in the textbox to search for an item I get this error:
The parameterized query '(#Parameter1 nvarchar(4000))SELECT * FROM
borrow where (Departme' expects the parameter '#Parameter1', which was
not supplied.
Can anyone help me?

If you pass null value to parameter,you will get this error even after you add the parameter
so try to check the value and if it null then use DBNull.Value
This will work
cmd.Parameters.Add("#Department", SqlDbType.VarChar)
If (TextBox2.Text = Nothing) Then
cmd.Parameters("#Department").Value = DBNull.Value
Else
cmd.Parameters("#Department").Value = TextBox2.Text
End If
This will convert the null values from the object layer to DBNull values that are acceptable to the database.

Your website is in serious danger of being hacked.
Read up on SQL Injection and how to prevent it in .NET
Your query problem is the least of your concerns right now.
But.....
#Misnomer's solution is close but not quite there:
Change your query to this:
cmd.CommandText = "SELECT * FROM borrow where (Department LIKE '%#DepartmentText%')"
and add parameters this way (or the way that #Misnomer does):
cmd.Parameters.AddWithValue("#DepartmentText",TextBox2.Text)
The important difference is that you need to change your CommandText.

Building on and simplifying ravidev's answer:
The VB.NET shorthand is:
cmd.Parameters.AddWithValue("#Department", IF(TextBox2.Text, DBNull.Value))
The C# shorthand is:
cmd.Parameters.AddWithValue("#Department", (object)TextBox2.Text ?? DBNull.Value)

Try adding parameters like this -
cmd.Parameters.Add("#Department", SqlDbType.VarChar)
cmd.Parameters("#Department").Value = TextBox2.Text
and change your command text to what #Abe Miessler does he is right i just thought you will figure it out.

If you are writing from a DataGridView control to your database, make sure there is no empty row. Set 'Allow User to add Rows' to false; it truncates the unnecessary last empty row.

SqlConnection conn = new SqlConnection(connectionString);
conn.Open();
//SelectCustomerById(int x);
comboBoxEx1.Items.Clear();
SqlCommand comm = new SqlCommand("spSelectCustomerByID", conn);
//comm.Parameters.Add(new SqlParameter("cust_name", cust_name));
//comm.CommandText = "spSelectCustomerByID";
comm.Parameters.Add(new SqlParameter("cust_id", SqlDbType.Int));
comm.CommandType = CommandType.StoredProcedure;
comm.ExecuteNonQuery();
SqlDataAdapter sdap = new SqlDataAdapter(comm);
DataSet dset = new DataSet();
sdap.Fill(dset, "cust_registrations");
if (dset.Tables["cust_registrations"].Rows.Count > 0)
{
comboBoxEx1.Items.Add("cust_registrations").ToString();
}
comboBoxEx1.DataSource = dset;
comboBoxEx1.DisplayMember = "cust_name";

Related

Updating Table from vb to Access using ConnectionString

Private Sub btnUpdate_Click(sender As Object, e As EventArgs) Handles btnUpdate.Click
Try
Dim con As New SqlConnection
Dim cmd As New SqlCommand
con.ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=E:\Comp-296\Project1\Project1\Game_time.mdb"
con.Open()
cmd.Connection = con
cmd.Connection = con
cmd.CommandText = ("UPDATE User_Name SET User_Name = #User_Name, Game_Name = #Game_Name, Score = #Score, Time/Date = #Time/Date")
cmd.Parameters.Add("#User_Name", SqlDbType.VarChar).Value = txtUser.Text
cmd.Parameters.Add("#Game_Name", SqlDbType.VarChar).Value = txtGame.Text
cmd.Parameters.Add("#Score", SqlDbType.VarChar).Value = txtScore.Text
cmd.Parameters.Add("#Time/Date", SqlDbType.DateTime).Value = txtDate.Text
cmd.ExecuteNonQuery()
MessageBox.Show("Data Update successfully")
con.Close()
Catch ex As System.Exception
MessageBox.Show("Data Update has failed")
End Try
End Sub
The code is giving an Exception is an ArgumentException and also :Keyword not supported: 'provider'.
You are using Access. This database cannot be opened using the classes in System.Data.SqlClient. These classes are used when you want to connect to Sql Server, Sql Server Express or LocalDB.
If you want to reach an MSAccess database you need the classes in System.Data.OleDb and these classes are OleDbConnection, OleDbCommand etc...
Said that, please note, that your field Date/Time will give you headaches. Change that name or put always square brackets around it because the / will be interpreted as the division operator
So your code could be:
Using con = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=E:\Comp-296\Project1\Project1\Game_time.mdb")
Using cmd = new OleDbCommand("UPDATE User_Name
SET User_Name = #User_Name,
Game_Name = #Game_Name,
Score = #Score, [Time/Date] = #dt", con)
con.Open()
cmd.Parameters.Add("#User_Name", OleDbType.VarWChar).Value = txtUser.Text
cmd.Parameters.Add("#Game_Name", OleDbType.VarWChar).Value = txtGame.Text
cmd.Parameters.Add("#Score", OleDbType.VarWChar).Value = txtScore.Text
cmd.Parameters.Add("#dt", OleDbType.Date).Value = Convert.ToDateTime(txtDate.Text)
cmd.ExecuteNonQuery()
MessageBox.Show("Data Update successfully")
End Using
End Using
Other notes:
Disposable objects like the connection and the command should be enclosed inside a Using Statement to be disposed and closed as soon as possible.
The time field requires a DateTime value not a string. If you pass a string you will face the automatic conversion made by the engine and sometime the engine is unable to produce a valid date from your input string. This will raise another exception (DataType mismatch). Better check and convert the value before passing it.
Also the type of the parameters should be from the OleDbType enum.

if the input value is in between two values then display the result

I have a SQL table with three columns "From","To" and "Equivalent Value". Each value is shown below:
From To Equivalent Value
1,001.00 2,000.00 200.00
2,001.00 3,000.00 300.00
Now if the user enters the value "1,200.00" in textbox1 it will display the result value to textbox2 which is "200.00" because that is the corresponding value of between "From" and "To.
Another condition, if the user enters the value "2,500.00" in textbox1 it will display the value "300.00".
So far, I have tried this code but no luck:
Dim conn As SqlConnection = SQLConn()
Dim da As New SqlDataAdapter
Dim dt As New DataTable
conn.Open()
Dim cmd As New SqlCommand("", conn)
Dim result As String
cmd.CommandText = "SELECT [Equivalent Value] FROM tblSSS"
result = IIf(IsDBNull(cmd.ExecuteScalar), "", cmd.ExecuteScalar)
da.SelectCommand = cmd
dt.Clear()
da.Fill(dt)
If result <> "" Then
If TextBox1.Text >= dt.Rows(0)(1).ToString() And TextBox1.Text <= dt.Rows(0)(2).ToString() Then
TextBox2.Text = dt.Rows(0)(3).ToString()
End If
End If
If I have got this right I think there are a couple of things I would change which may help you:
Use Using. This will dispose of the SQL objects once finished with.
Use SqlParameters. This will help with filtering your data.
Remove the use of SqlDataAdapter. In this case I don't feel it's needed.
The use of IIf. I will be using If which has replaced IIf.
With these in mind I would look at something like this:
Dim fromValue As Decimal = 0D
Dim toValue As Decimal = 0D
If Decimal.TryParse(TextBox1.Text, fromValue) AndAlso Decimal.TryParse(TextBox1.Text, toValue) Then
Dim dt As New DataTable
Using conn As SqlConnection = SQLConn,
cmd As New SqlCommand("SELECT [Equivalent Value] FROM tblSSS WHERE [From] >= #From AND [To] <= #To", conn)
cmd.Parameters.Add(New SqlParameter With {.ParameterName = "#From", .SqlDbType = SqlDbType.Decimal, .Value = fromValue})
cmd.Parameters.Add(New SqlParameter With {.ParameterName = "#To", .SqlDbType = SqlDbType.Decimal, .Value = toValue})
conn.Open()
dt.Load(cmd.ExecuteReader)
End Using
If dt.Rows.Count = 1 Then
TextBox2.Text = If(IsDBNull(dt.Rows(0).Item("Equivalent Value")), "0", dt.Rows(0).Item("Equivalent Value").ToString)
End If
End If
Note the use of Decimal.TryParse:
Converts the string representation of a number to its Decimal equivalent. A return value indicates whether the conversion succeeded or failed.
This is an assumption that the From and To fields in your database are Decimal.
Now to explain the difference between IIf and If. IIf executes each portion of the statement even if it's true whilst If executes only one portion. I won't go into detail as many others on here have done that already. Have a look at this answer.
As per Andrew Morton's comment and more in line with what the OP attempted here is a solution that uses ExecuteScaler.
ExecuteScaler executes the query, and returns the first column of the first row in the result set returned by the query. Additional columns or rows are ignored.
With this in mind:
'I reset the value of TextBox2.Text. You may not want to.
TextBox2.Text = ""
Dim fromValue As Decimal = 0D
Dim toValue As Decimal = 0D
If Decimal.TryParse(TextBox1.Text, fromValue) AndAlso Decimal.TryParse(TextBox1.Text, toValue) Then
Using conn As SqlConnection = SQLConn,
cmd As New SqlCommand("SELECT [Equivalent Value] FROM tblSSS WHERE [From] >= #From AND [To] <= #To", conn)
cmd.Parameters.Add(New SqlParameter With {.ParameterName = "#From", .SqlDbType = SqlDbType.Decimal, .Value = fromValue})
cmd.Parameters.Add(New SqlParameter With {.ParameterName = "#To", .SqlDbType = SqlDbType.Decimal, .Value = toValue})
conn.Open()
Try
TextBox2.Text = cmd.ExecuteScalar().ToString()
Catch ex As Exception
End Try
End Using
End If
I have used the example on the ExecuteScaler MSDN documentation. You might want to look into handling the exception on the Try Catch a little better and not letting it go to waste.
You may want to place this code on the TextBox1.Leave method or maybe on a Button.Click method. That's totally up to you.
There may a few changes you may need to make however I think this will give you a few ideas on how to move ahead with your code.
Hope it Helps...
Dim connetionString As String
Dim cnn As SqlConnection
Dim cmd As SqlCommand
Dim sql As String
connetionString = "Data Source=ServerName;Initial Catalog=DatabaseName;User ID=UserName;Password=Password"
sql = "SELECT [Equivalent Value] FROM tblSSS WHERE [FROM]<=" & Val(TextBox1.Text) & " AND [TO]>= " & Val(TextBox1.Text)
cnn = New SqlConnection(connetionString)
Try
cnn.Open()
cmd = New SqlCommand(sql, cnn)
Dim count As Int32 = Convert.ToInt32(cmd.ExecuteScalar())
cmd.Dispose()
cnn.Close()
Catch ex As Exception
MsgBox("Can not open connection ! ")
End Try

Error on Search Button

I searched on some codes on how to do a Search Button in VB.net. But somehow, it won't work because of an error. And simply because, I cannot understand its algorithm and function. Newbie here. Anyway, here is the code for the search button:
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
myConnection.Open()
crd.Clear()
fn.Clear()
ln.Clear()
Dim str As String
str = "SELECT * FROM tblReg WHERE (Code = '" & src.Text & "')"
Dim cmd As OleDbCommand = New OleDbCommand(str, myConnection)
dr = cmd.ExecuteReader
While dr.Read()
crd.Text = dr("crd").ToString
fn.Text = dr("fName").ToString
ln.Text = dr("lName").ToString
End While
myConnection.Close()
End Sub
And the error was on:
dr = cmd.ExecuteReader
And VB said:
An unhandled exception of type 'System.Data.OleDb.OleDbException' occurred in System.Data.dll
Additional information: No value given for one or more required parameters.
One should not follow online tutorials that teach very bad code. That code is very bad because it contains SQL injection and leaves database objects opened.
You should rewrite your code as follows:
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
myConnection.Open()
crd.Clear()
fn.Clear()
ln.Clear()
Using cmd = New OleDbCommand("SELECT * FROM tblReg WHERE Code = ?", myConnection)
cmd.CommandType = CommandType.Text
With cmd.Parameters.Add(Nothing, OleDbType.VarChar, 50)
.Direction = ParameterDirection.Input
.Value = src.Text
End With
Using dr = cmd.ExecuteReader()
While dr.Read()
crd.Text = dr("crd").ToString
fn.Text = dr("fName").ToString
ln.Text = dr("lName").ToString
End While
End Using
End Using
myConnection.Close()
End Sub
You have to use question marks in place of parameters because you are using OleDbCommand that does not support named parameters.
Change OleDbType.VarChar to your actual column type.
Is this the link where you get the code?
http://www.visual-basic-tutorials.com/ReadFromAccess.htm
Kindly do not get the code read each data on the output shows and also check this part of the code.
crd.Text = dr("crd").ToString
fn.Text = dr("fName").ToString
ln.Text = dr("lName").ToString
are you sure crd,fname,lname are the name of your fields in your table? pls check it and also what is the field type of code? is it a text or INT that is Auto Increment? or just an INT? no matter what it is change your code.
from
str = "SELECT * FROM tblReg WHERE (Code = '" & src.Text & "')"
to
str = "SELECT * FROM tblReg WHERE Code =" & src.Text
Updated
I suggest better read or follow the whole instruction based on link where you get your code. I suggest do the same as what the link said create the same and when the program runs with no error then incorporate it with your program beacuse I tried it using VB.NET and Access and it worked Im sure you dont read it. Do this and Im sure you will not just get the code you need you will also learn.

get picture from database(close)

this is my success code:
Private Sub dg1_CellClick(sender As Object, e As DataGridViewCellEventArgs) Handles dg1.CellContentClick
Label5.Text = dg1.Item(0, e.RowIndex).Value
Label6.Text = dg1.Item(2, e.RowIndex).Value
con.ConnectionString = "Data Source=(LocalDB)\v11.0;AttachDbFilename=C:\USERS\USER\DOWNLOADS\SDP(BACKUP1)\SDP(BACKUP)\SDP.MDF;Integrated Security=True"
con.Open()
cmd.Connection = con
cmd.CommandText = "select picture from Announcement where name = #name"
cmd.Parameters.AddWithValue("#name", dg1.CurrentRow.Cells(0).Value())
da.SelectCommand = cmd
Dim imageData As Byte() = DirectCast(cmd.ExecuteScalar(), Byte())
If Not imageData Is Nothing Then
Using ms As New MemoryStream(imageData, 0, imageData.Length)
ms.Write(imageData, 0, imageData.Length)
PictureBox2.Image = Image.FromStream(ms, True)
End Using
End If
End Sub
i had success get my picture from database. which add paramater to name, then parameter name with #name.
You're not loading a picture from a DataGridView at all. You're trying to query a database and it's failing. Nothing to do with grids or images. Plain and simple, you've written bad SQL code. If you're going to include a text literal then it needs to have single quotes around it. Better still, do it properly and use parameters.
The issue is, as I have said, in your SQL code:
cmd.CommandText = "select picture from Announcement where name =" & dg1.Item(0, e.RowIndex).Value & ""
You are inserting a value for the name column into that SQL code so it becomes text literal. As I said, text literals require single quotes. Where are your single quotes? You don't have any. That's the issue. If you were going to use string concatenation like that, which you should not, then it would need to look like this:
cmd.CommandText = "select picture from Announcement where name = '" & dg1.Item(0, e.RowIndex).Value & "'"
If you were to do it properly, which involves using parameters, as I said, then it would look something like this:
cmd.CommandText = "select picture from Announcement where name = #name"
cmd.Parameters.AddWithValue("#name", CStr(dg1.Item(0, e.RowIndex).Value))
or like this:
cmd.CommandText = "select picture from Announcement where name = #name"
cmd.Parameters.Add("#name", SqlDbType.VarChar, 50).Value = CStr(dg1.Item(0, e.RowIndex).Value)

Syntax error in VB.NET application using SQL

Hi I have been learning VB.NET for about a month now. I am stuck on something I get an error message saying
Syntax error in union query.
The code in question is this.
Private Sub Button5_Click_1(sender As Object, e As EventArgs) Handles Button5.Click
Dim Builder As New OleDb.OleDbConnectionStringBuilder With
{
.Provider = "Microsoft.ACE.OLEDB.12.0",
.DataSource = IO.Path.Combine(Application.StartupPath, "C:\Users\Nige\Documents\Visual Studio 2012\Projects\MS_Access_SimplePassword\bin\Debug\Database1.mdb"),
.PersistSecurityInfo = True
}
LoginForm.txtUserName.Text = LoginForm.txtUserName.Text
If LoginForm.txtUserName.Text <> "" Then
End If
'do what you want to do
lblName.Text = LoginForm.txtUserName.Text
If lblName.Text = LoginForm.txtUserName.Text Then
Builder.Add("Jet OLEDB:Database Password", "password")
Using con As New OleDb.OleDbConnection With {.ConnectionString = Builder.ConnectionString}
Using cmd As New OleDb.OleDbCommand With
{
.Connection = con,
.CommandText =
<SQL>
("SELECT * FROM tblContacts WHERE number" = '55')
Identifier,
UserName,
UserPassword,
UserTimer
FROM tblContacts
</SQL>.Value
}
con.Open()
Dim Reader As OleDb.OleDbDataReader = cmd.ExecuteReader
If Reader.HasRows Then
Reader.Read()
TextBox1.Text = Reader.GetInt32(0).ToString
TextBox2.Text = Reader.GetString(1)
TextBox3.Text = Reader.GetString(2)
TextBox4.Text = Reader.GetString(3)
End If
End Using
End Using
End If
End Sub
The code above was supposed to when I click button5 search my "ms access database" called "tblContacts" for a row that references the number "55"
If my code looks strange in places it because I am a still on a learning path :)
Cheers
I can see a couple of errors in your code above:
Dim Builder As New OleDb.OleDbConnectionStringBuilder With
{
.Provider = "Microsoft.ACE.OLEDB.12.0",
.DataSource = "C:\Users\Nige\Documents\Visual Studio 2012\Projects\MS_Access_SimplePassword\bin\Debug\Database1.mdb"),
.PersistSecurityInfo = True
}
That Path.Combine with two absolute filename is logically wrong, but, nevertheless it works because Path.Combine is able to recognize that the two strings passed are two full filename and thus doesn't try to create an impossible path, but return directly the second string.
From MSDN on Path.Combine
The combined paths. If one of the specified paths is a zero-length
string, this method returns the other path. If path2 contains an
absolute path, this method returns path2.
Then, looking at your query, it clearly an invalid text for a select and thus you get the Syntax Error.
This could be the correct way to query the datatable assuming
You search for a row with a column named 'number'
This column is of text type text
One or more rows contains in this column a text equals to '55'
Dim sqlText = "SELECT Identifier, UserName, UserPassword, UserTimer " +
"FROM tblContacts WHERE number = '55'";
Using con = New OleDb.OleDbConnection(Builder.ConnectionString)
Using cmd = New OleDb.OleDbCommand(sqlText, con)
con.Open()
Using Reader = cmd.ExecuteReader
While Reader.Read()
TextBox1.Text = Reader.GetInt32(0).ToString
TextBox2.Text = Reader.GetString(1)
TextBox3.Text = Reader.GetString(2)
TextBox4.Text = Reader.GetString(3)
End While
End Using
End Using
End Using