Update Query in Visual Basic Express 2010 - sql

I'm trying to update an Access 2003 database using Visual Basic Express 2010 via SQL, I have so far got SELECT, DELETE and INSERT queries to work, but update will not...
con.ConnectionString = dbProvider & dbSource
con.Open() 'Open connection to the database
sqlstatement = "UPDATE users SET password = '" & NewPassword & "' WHERE USERID = " & ID & ";"
Dim dc As New OleDb.OleDbCommand(sqlstatement, con)
dc.ExecuteNonQuery()
con.Close()
Like I said, all other statements work, the error produced is:
http://i.stack.imgur.com/acFBT.png
Thank you!

The first problem is the word PASSWORD. It is a reserved keyword in MS-Access database. If you want to use it you should enclose it in square brackets.
Said that, please start using a parameterized query and not a string concatenation when you work with any type of database
So your code should be:
sqlstatement = "UPDATE users SET [password] = ? WHERE USERID = ?"
Using con = new OleDbConnection(dbProvider & dbSource)
Using dc = new OleDbCommand(sqlstatement, con)
con.Open()
dc.Parameters.AddWithValue("#p1", NewPassword)
dc.Parameters.AddWithValue("#p2", ID)
dc.ExecuteNonQuery()
End Using
End Using
You could read about the importance of Parameterized Queries and Sql Injection in many places, this link is a most famous one to start with

Related

Error executing query when encountering name containing an apostrophe (e.g. O'Conner)

My database program has a statement like:
variable = "SELECT * from Staff where StaffName = '" & cStaffName & "'"
This works fine until I have a member of staff with ' (apostrophe) in there name as it ends the start apostrophe.
SELECT * from Staff where StaffName = 'O'Conner'
Is there a way around this without replacing the apostrophe in her name?
You just need to use a parameterized query.
Using con = new SqlConnection(....)
Using cmd = new SqlCommand("SELECT * from Staff where StaffName = #name", con)
con.Open
cmd.Parameters.Add("#name", SqlDbType.NVarChar).Value = cStaffName
Using reader = cmd.ExecuteReader
.....
End Using
End Using
End Using
In this scenario you add a parameter to the SqlCommand parameters collection. The command text has no more a string concatenation but contains a parameter placeholder (#name). The parameter itself contains the value you want to pass to your query.
In this way there is no problem with quotes embedded in the value.
You also get the extra benefit to avoid any kind of Sql Injection problem with the user input
variable = "SELECT * from Staff where StaffName = '" & Replace(cStaffName, "'", "\'") & "'"

search for a field between two dates in vb.net

My information in database is weak and I do not know how to use queries. I have searched the web and I learned few thing about making queries and I found an example but i do not know how to use it in vb.net.
The query in SQL server will be like this:
select hb from gen where date between 12/6/2014 and 16/6/2014
It works fine, but i don't know how to use it in vb.net
so wrote this line of code and i think my solution will be something like this:
BindingSource1.Filter = String.Format("select hb from gen where date between" & DateTimePicker1.Value & "and" & GENDateTimePicker1.Value)
so what is wrong with this line
If you'd read the documentation then you'd know that the BindingSource.Filter property requires dates to be expressed in the format #M/dd/yyyy#. Also, the String represents just a WHERE clause, not an entire query. You're not using String.Format properly either. Your code should be:
BindingSource1.Filter = String.Format("[Date] BETWEEN #{0:M/dd/yyyy}# AND #{1:M/dd/yyyy}#", DateTimePicker1.Value, GENDateTimePicker1.Value)
Here is an example on how to use your sql query in vb.net:
First, you want to setup your connection string to your database. Next, you can declare a string with the contents of your sql statement. Third, you'll want to setup a using statement that will close the sql connection when it exits. I would also read up on parameterized sql to mitigate attacks on your database.
Dim con As String = (ConfigurationManager.ConnectionStrings("YOURCONNECTIONSTRINGNAME").ConnectionString)
Dim result as String = String.Empty 'set the result to whatever the datatype of hb is in your database
Dim query as String = "select hb from gen where date between '12-6-2014' and '16-6-2014'"
Using conn As New SqlClient.SqlConnection(con)
Try
conn.Open()
Dim command As New SqlClient.SqlCommand(query, conn)
command.Connection = conn
command.CommandType = CommandType.Text
result = command.ExecuteScalar()
conn.Close()
conn.Dispose()
Catch ex As Exception
System.Diagnostics.Debug.WriteLine(ex.Message)
End Try
End Using
this is the solution which i made after hard searching and a lot of lectures in vb.net and SQL server "Excuse me I am a beginner"
Me.BindingSource1.Filter = String.Format(" date <= #{0:M/dd/yyyy}# AND Date >= #{1:M/dd/yyyy}# and hb like'" & TextBox1.Text & "%'", DateTimePicker1.Value, DateTimePicker2.Value)
and "hb" is the name of the field which i want to find
thank you for your time and the fast respond

How can I use where function using insert into module

My command is error in my sql command where clause, how can I handle it? any suggestion or any help?
This is my Error:
syntax to use near 'WHERE controlNumber = '' at line 1
cmd = New Odbc.OdbcCommand("INSERT INTO alamnotice (correctivePreventive) VALUES('" & Trim(txtremarks.Text.TrimEnd()) & "') WHERE controlNumber ='" & Trim(Form1.txtcontrolNumber.Text.TrimEnd()) & "'", con)
cmd.ExecuteNonQuery()
You havent said what the error is, it could be something to do with Disconnect, but I suspect it is a SQL syntax error because INSERT doesnt use a WHERE (you are inserting new data).
Here is a way to use params to make the code easier to read and avoid SQL injection attacks:
Dim SQL As String = "INSERT INTO alamnotice (correctivePreventive,
sectionInCharge, shiftInCharge, SectionHead, status,
dateResponded, remarksSurrendingAlarm, Remarks)
VALUES ("#p1", "#p2", "#p3", "#p4", "#p5", "#p6", "#p7", "#p8")"
' I am assuming OleDB, but much the same for others
' be sure to add the values in the same order with OleDB
Using cmd As New OleDbCommand(SQL, dbCon)
cmd.Parameters.AddWithValue("#p1", txtcorPrevAction.Text )
cmd.Parameters.AddWithValue("#p2", txtCause.Text)
cmd.Parameters.AddWithValue("#p3", cmbstatus.Text)
' etc
cmd.ExecuteNonQuery()
End Using
for non string columns, such as a date, convert the textbox text:
cmd.Parameters.AddWithValue("#pX", COnvert.ToInt32(txtSomeValue.Text))
the code is easier to read and if you arent gluing ticks and stuff into a string, there are far fewer string format errors like a missing '
try this one :
UPDATE alamnotice SET correctivePreventive = '" & Trim(txtremarks.Text.TrimEnd()) & "' WHERE controlNumber ='" & Trim(Form1.txtcontrolNumber.Text.TrimEnd()) & "'"

How do I update my database with the content of a TextBox?

I have a database table with three columns: User, Pass, Money. I also have a vb form with a button and a TextBox named Money. What's the query code for updating the Money in the database, so it would be the same as the TextBox in the form?
Check Link , You are probably looking for it .
an update query can be
UPDATE Categories
SET Money = #MoneyTextBox WHERE (user = #currentUser)
With this piece of code you should be able to connect and update an Access database
Dim Connection As New OledbConnection("Provider=microsoft.Jet.oledb.4.0;DataSource=YourDatabase.mdb;")
Try
Connection.Open()
Dim Query = "UPDATE TableName SET Money = ? WHERE User = ?"
Dim command As New OleDbCommand
With command
.CommandText = Query
.Connection = Connection
.Parameters.AddWithValue("#p1", MoneyTextBox.Text)
.Parameters.AddWithValue("#p2", UserTextBox.Text)
End With
command.ExecuteNonQuery()
Catch exception As Exception
MessageBox.Show(exception.Message)
Finally
Connection.Close()
End Try
use Update Query
"update Databasename set Money='"& MoneyTextBox.Text &"' where user='" & UserTextBox.Text &"' and Pass='"PassTextBox.Text"' "

Error in My Add button SQL Server Management Studio And Visual Basic 2010

Here is the thing I can't use insert query in my code there is an error in my SqlCommand that says the ExecuteNonQuery() not match with the values blah blah
Here is my code
Dim con As New SqlClient.SqlConnection("Server=.\SQLExpress;AttachDBFilename=C:\Program Files\Microsoft SQL Server\MSSQL10_50.SQLEXPRESS\MSSQL\DATA\Finals.mdf;Database=Finals;Trusted_Connection=Yes;")
Dim cmd As New SqlClient.SqlCommand
cmd.Connection = con
cmd.CommandText = "Insert Into [Finals].[dbo].[Nokia] Values ('" & Unit.Text & "'),('" & Price.Text & " '),('" & Stack.Text & "'),('" & Processor.Text & "'),('" & Size.Text & "'),('" & RAM.Text & "'),('" & Internal.Text & "'),('" & ComboBox1.Text & "')"
con.Open()
cmd.ExecuteNonQuery()
con.Close()
The problem is the cmd.CommandText can anyone please help me?
You need to rewrite your query to use a parameterized query. This would avoid parsing problems if your textboxes contains single quotes and, most important, would remove any possibility of Sql Injection.
So you code could look like this
Dim cmdText = "Insert Into [Finals].[dbo].[Nokia] Values (#unit, #price,#stack," & _
"#processor,#size,#ram,#internal,#lastvalue"
Using con As New SqlConnection(......)
Using cmd As New SqlCommand(cmdText, con)
con.Open()
cmd.Parameters.AddWithValue("#unit",Unit.Text )
cmd.Parameters.AddWithValue("#price",Price.Text)
cmd.Parameters.AddWithValue("#stack",Stack.Text)
cmd.Parameters.AddWithValue("#processor", Processor.Text)
cmd.Parameters.AddWithValue("#size",Size.Text)
cmd.Parameters.AddWithValue("#ram", RAM.Text)
cmd.Parameters.AddWithValue("#internal",Internal.Text)
cmd.Parameters.AddWithValue("#lastvalue", ComboBox1.Text)
cmd.ExecuteNonQuery()
End Using
End Using
Said that, be aware of two more problems:
You don't specify a column list before the VALUES statement. This means that you need to pass the exact number of parameters for every column present in your table named Nokia AND in the EXACT ORDER of the underlying columns. If you forget one parameter you will receive an exception and if you swap the order of the parameters you end writing your data in the wrong column (with an exception waiting for you if the datatype doesn't match).
The second problem concerns the datatype of every parameter passed to the query. In your case you use the Text property of the textboxes and this means that you are passing a string for every column in the datatable. Of course, if a column expects a numeric value you get a mismatch error.
For example the #price parameter could be used to update a decimal column in the datatable and thus you need to convert the parameter from string to decimal before adding it using the AddWithValue method
cmd.Parameters.AddWithValue("#price",Convert.ToDecimal(Price.Text))