vb.net sql parameterization - sql

I really need help this time. I search everywhere, tried numerous solutions. but i can't seem to solve my problem. Now i'm going to ask, please help. I have been having this problem for a week now.
ExecuteSQL("select * from account_database where idnum= #idnum and password= #pass")
'Dim idnum As New SqlParameter("#idnum", SqlDbType.VarChar)
'Dim pass As New SqlParameter("#pass", SqlDbType.VarChar, -1)
'idnum.Value = idnumtxt.Text
'pass.Value = output
'cmd.Parameters.Add(idnum)
'cmd.Parameters.Add(pass)
cmd.Parameters.Add("#idnum", SqlDbType.VarChar).Value = idnumtxt.Text
cmd.Parameters.Add("#pass", SqlDbType.VarChar, -1, "password").Value = output
those commented out lines are the codes which i have tried, also there are codes which i implemented that also failed.
The error message concludes as "Must declare scalar variable #idnum"
i really need help please. Please shine some light.
This is the code what the function executeSQL contains :
Public Shared Sub ExecuteSQL(ByVal strSQL As String)
Try
If connection.State = 1 Then ' check connection if open
connection.Close()
End If
' connection
connection.ConnectionString = "Data Source=.\SQLEXPRESS;AttachDbFilename=C:\Users\Jr\documents\visual studio 2010\Projects\VotingSystem\VotingSystem\Resources\Database.mdf;Integrated Security=True;User Instance=True"
connection.Open()
Dim rowAffected As Integer = 0
'cmd = New SqlCommand(strSQL, connection) 'buiding the sql command with the use of strSQL (sql statement) and connection (database connection)
cmd = New SqlCommand(strSQL, connection)
DARec = New SqlDataAdapter(strSQL, connection) 'buiding the adapter
cb = New SqlCommandBuilder(DARec)
rowAffected = cmd.ExecuteNonQuery() 'executing of sql statement
successID = 1
connection.Close()
Catch ex As Exception
successID = 0
MsgBox(ex.Message)
End Try
End Sub
Thanks and please help.

Problem is simply you're doing this in the wrong order. You're attempting to execute your SQL statement before defining the parameters. You don't need ExecuteSQL() until you've defined your parameters. It likely breaks on the following line in ExecuteSQL()
' See how many rows the query will impact
' Since #idnum and #pass are not defined until the
' ExecuteSQL() sub is finished, this line breaks.
rowAffected = cmd.ExecuteNonQuery()
You need to build your SqlCommand() to first include the select statement, and then use AddWithValue() on the parameters you've defined in the string. Defining the datatypes is also unnecessary because your database already knows, and form validation should handle input.
' Define your connection
connection.ConnectionString = "Data Source=.\SQLEXPRESS;AttachDbFilename=C:\Users\Jr\documents\visual studio 2010\Projects\VotingSystem\VotingSystem\Resources\Database.mdf;Integrated Security=True;User Instance=True"
' Setup your SQL Command.
cmd = New SqlCommand("select * from account_database where idnum = #idnum and password = #pass", connection)
' Define the parameters you've created
cmd.Parameters.AddWithValue("#idnum", idnumtxt.Text)
cmd.Parameters.AddWithValue("#pass", output)
' Now execute your statement
connection.open()
cmd.ExecuteNonQuery()
connection.close()
And here is a better version of the above code, since you understand the order of events now. This ensures that in the event of exception the connection is closed.
strConn = "Data Source=.\SQLEXPRESS;AttachDbFilename=C:\Users\Jr\documents\visual studio 2010\Projects\VotingSystem\VotingSystem\Resources\Database.mdf;Integrated Security=True;User Instance=True"
strSQL = "select * from account_database where idnum = #idnum and password = #pass"
Using connection As New SqlConnection(strConn), cmd As SqlCommand(strSQL, connection)
cmd.Parameters.Add("#idnum", SqlDbType.VarChar).Value = idnumtxt.Text
cmd.Parameters.Add("#pass", SqlDbType.VarChar, -1, "password").Value = output
connection.Open()
cmd.ExecuteNonQuery()
End Using

Try this:
cmd.Parameters.AddWithValue("idnum", idnumtxt.Text)
Reference:
SqlParameterCollection.AddWithValue # MSDN.

It should just be a case of the following to add an input param
cmd.Parameters.Add("#idnum", idnumtxt.Text)
Except you'll need cmd.parameters.add() before the executesql as you're currently defining your params after executesql has ran.

Related

Why does jgejala = drkonsultasi.item(0) evaluate to invalid operation?

I have this code:
comkonsultasi = New OleDbCommand("select count(idkonsultasi) from dkonsultasi where idgejala='" & idgejala & "'", conn)
drkonsultasi = comkonsultasi.ExecuteReader
jgejala = drkonsultasi.Item(0)
When it runs, I get this exception message on the last line:
InvalidOperationException was unhandled. No data exists for the row/column.
Can anyone can help to resolve this problem?
You have to Read() from the DataReader. It's also very bad to use string concatenation to put data into an SQL query like that. You must use query parameters instead:
Dim sql As String = "select count(idkonsultasi) from dkonsultasi where idgejala= ?"
Using conn As New OleDbConnection("connection string here"), _
comkonsultasi As New OleDbCommand(sql, conn)
'Use the actual type and length from the database for this line
comkonsultasi.Parameters.Add("idgejala", OleDbType.VarWChar, 50).Value = idgejala
conn.Open()
Using drkonsultasi As OleDbDataReader = comkonsultasi.ExecuteReader()
If drkonsultasi.Read() Then
jgejala = drkonsultasi.Item(0)
End Using
End Using
End Using

could not update currently locked vb.net error

I want to Insert 2 different data in 2 different table of ms-access.
And it shows this error.
I have a code like this:
try
dim sql1,sql2 as string
sql1 = "INSERT INTO table1(something)VALUES(something)"
cmd = new oledbcommand(sql1, connection)
cmd.executenoquery()
sql2 = "INSERT INTO table2(something)VALUES(something)"
cmd2 = new oledbcommand(sql2, connection)
cmd2.executenoquery()
catch ex as exception
msgbox(ex.tostring())
(where these cmd1,cmd2 are defined in controlModule.)
so,what should I do ?
Any help is appreciated. Thank You
I think closing the connection fixes the issue, best by using the Using-statement:
try
Using con As OleDbConnection = GetConnection() ' or New OlebConnection(...)
Using cmd = con.CreateCommand()
cmd.CommandText = "INSERT INTO table1(something)VALUES(#something)"
cmd.Parameters.AddWithValue("#something", something)
con.Open()
cmd.ExecuteNonQuery()
End Using
End Using
Using con As OleDbConnection = GetConnection()
Using cmd = con.CreateCommand()
cmd.CommandText = "INSERT INTO table2(something)VALUES(#something)"
cmd.Parameters.AddWithValue("#something", something)
con.Open()
cmd.ExecuteNonQuery()
End Using
End Using
Catch ex As Exception
msgbox(ex.tostring())
End Try
This is a concurrency issue. Because some other part of your code or MS Access itself accesses the database at the same time.
The fact is that you're not closing the connection after it's use. So the 2nd call should fail with that exception. Instead, you should wrap your disposables - e.g. the OleDbConnection, commands, etc. - in a using statement. That way, the connection will be closed, even if an exception occur:
Using con As New OleDbConnection, cmd1 As OleDbCommand = con.CreateCommand, cmd2 As OleDbCommand = con.CreateCommand()
cmd1.CommandText = "INSERT INTO table1(something)VALUES(something)"
cmd1.ExecuteNonQuery()
cmd2.CommandText = "INSERT INTO table2(something)VALUES(something)"
cmd2.ExecuteNonQuery()
End Using

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.

How to count number of rows in a sql table with vb.net using sqlclient class

SELECT count(*) FROM table name
this above code work fine in standalone sql table, but who can I do this simple task with in vb.net wpf project ?
This is only a sample ..just check and try your own way.
Sample:
Dim connetionString As String
Dim connection As SqlConnection
Dim command As SqlCommand
Dim sql As String
connetionString = "Data Source=ServerName;Initial Catalog=DatabaseName;
User ID=UserName;Password=Password"
sql = "Select count(*) from table"
connection = New SqlConnection(connetionString)
Try
connection.Open()
command = New SqlCommand(sql, connection)
Dim sqlReader As SqlDataReader = command.ExecuteReader()
While sqlReader.Read()
MsgBox("Count =" & sqlReader.Item(0))
End While
sqlReader.Close()
command.Dispose()
connection.Close()
Catch ex As Exception
MsgBox("Can not open connection ! ")
End Try
If your query return more than one values you can use SqlDataReader(), but if you are sure your query will return only a single value you can use ExecuteScalar() and if your query wont return any result, eg:- insert.it will insert value not return any data so we can use ExecuteNonQuery().The ExecuteNonQuery() will return a result which indicate is it successful or failure. If you want you can assign the same else no need.
Use SqlCommand.ExecuteScalar() method to execute query that return singular/scalar value (example based on that link) :
Dim count As Integer
Dim connString = "connection string to your database here"
Using conn As New SqlConnection(connString)
Dim cmd As New SqlCommand("SELECT COUNT(*) FROM MyTable", conn)
Try
conn.Open()
count = Convert.ToInt32(cmd.ExecuteScalar())
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
End Using

Error: Variable Names must be unique within a query batch or stored procedure

I successfully retrieve all my data from my database but whenever i try it for a second time an error occured saying that the variable name #uid has already been declared..
these are my codes. I dispose my sqlcommandbuilder and close my datareader everytime i used it.. but still no luck in finding the error at my codes.. please help me.. and also whenever i save and update data on my database.. it always succeed on the first try.. but on the second try.. it gets the same error "Variable Names must be unique within a query batch or stored procedure".
Sub fillDataFields()
Dim arrImage As Byte()
con.Open()
comm.CommandText = "Select last_name + ', ' + first_name + ' ' + middle_name as name,course, section, address, " & _
"birthday, picture from Users where user_id like #uid"
comm.Connection = con
comm.Parameters.AddWithValue("#uid", "" & frmUsers.ListView1.SelectedItems(0).Text & "%")
dr = comm.ExecuteReader
While (dr.Read())
arrImage = dr.Item("picture")
Dim mstream As New System.IO.MemoryStream(arrImage)
txtCourse.Text = (dr("course"))
txtSection.Text = (dr("section"))
richtxtAddress.Text = (dr("address"))
txtBirthday.Text = (dr("birthday"))
txtName.Text = (dr("name"))
PictureBox1.Image = Image.FromStream(mstream)
End While
con.Close()
dr.Close()
comm.Dispose()
End Sub
Your command object still has the parameter attached to it, so you should make sure you create a new instance of your objects and properly dispose of them after you have finished:
con = New Connection("connection string here")
con.Open()
comm = New Command
comm.CommandText = "command text here"
Then after you have finished with it dispose of it:
comm.Dispose
con.Close
con.Dispose
Even better wrap it in a Using block as this ensures it is disposed of for you:
Using con As New Connection("your connection String Here"), comm as New Command
con.Open()
comm.CommandText = "command text here"
...
...
con.Close
End Using 'con and comm objects are disposed here
Side note: I would suggest renaming your Command object something like cmd so that it doesn't look so similar to the Connection object.