how to insert data through VB.NET - vb.net

I am trying to pass my query string into database using VB.NET, but I am seeing a syntax error. I don't know where it is, please help me!
Me.str = String.Concat(New String()
{"Insert into Sales values('",
Me.txtVoucherNo.Text, "','", dtpDate.Value, "','",
dtpMonth.Value, "','", POSPage.txtPatientNo.Text, "','",
POSPage.txtPatientName.Text, "','",
POSPage.txtAddress.Text, ",'--',", POSPage.txtsubtotal.Text, "','",
POSPage.txtTax.Text, ",'--',", POSPage.txtdiscount.Text, "','",
POSPage.txtGrandTotal.Text, "')"})

Nooooooooooooo!
String edits like that leave you vulnerable to sql injection attacks. It's practically begging to get hacked.
You want something more like this:
Using cn As New SqlConnection(" connection string here "), _
cmd As New SqlCommand(
"Insert into Sales VALUES ( #VoucherNo, #Date, #Month, #PatientNo, #PatientName, #Address, '--', #SubTotal, #Tax, '--', #Discount, #GrandTotal )"
, cn )
'change this to use the actual column types and lengths in your database
cmd.Parameters.Add("#VoucherNo", SqlDbType.NVarChar, 10).Value = Me.txtVoucherNo.Text
cmd.Parameters.Add("#Date", SqlDbType.DateTime).Value = dtpDate.Value
cmd.Parameters.Add("#Month", SqlDbType.DateTime).Value = dtpMonth.Value
cmd.Parameters.Add("#PatientNo", SqlDbType.NVarChar, 10).Value = POSPage.txtPatientNo.Text
cmd.Parameters.Add("#PatientName", SqlDbType.NVarChar, 50).Value = POSPage.txtPatientName.Text
cmd.Parameters.Add("#Address", SqlDbType.NVarChar, 250).Value = POSPage.txtAddress.Text
cmd.Parameters.Add("#SubTotal", SqlDbType.Decimal).Value = Convert.ToDecimal(POSPage.txtsubtotal.Text)
cmd.Parameters.Add("#Tax", SqlDbType.Decimal).Value = Convert.ToDecimal(POSPage.txtTax.Text)
cmd.Parameters.Add("#Discount", SqlDbType.Decimal).Value = Convert.ToDecimal(POSPage.txtdiscount.Text)
cmd.Parameters.Add("#GrandTotal", SqlDbType.Decimal).Value = Convert.ToDecimal(POSPage.txtGrandTotal.Text)
cn.Open()
cmd.ExecuteNonQuery()
End Using
Note that, with this code, the SQL string itself is constant. Instead of a string field in your class (Me.Str), you need the full SqlCommand object, so that you can hold both the sql statement and the parameter data.
If you still have trouble with this, try including the names of the columns before the VALUES() clause.
That out of the way, original syntax error was because of this sequence in your string array:
"','", POSPage.txtAddress.Text, ",'--',"
Note that this would open a quoted field in your query, but not close it until after the comma. What comes next is a comment marker in Sql Server. In short, if you actually enter the name of the field as the address, you'd get this:
'POSPage.txtAddress.Text,'--
Everything after the two hyphens would be commented out, including the closing parentheses for your VALUES clause, meaning the query is not valid SQL syntax... assuming someone hasn't already used sql injection on another field to include put whatever sql statement they want as part of the query.
I won't tell you how to just fix that error, because it should be obvious now, and well... there's that pesky injection problem again. I will say that you made the same mistake with the other ",'--'," string later in the query.

Related

How to select MONTH() and YEAR() using SELECT query

Basically, I want to run a query to pull data entered into a VB form (specifically MONTH and YEAR).
This is what I currently have:
SELECT * FROM orders WHERE MONTH(date_ordered) = ? AND YEAR(date_ordered) = ? ;
When I run this in my database, it doesn't work. I get no results.
However, if I put it like this:
SELECT * FROM orders WHERE MONTH(date_ordered) = 08 AND YEAR(date_ordered) = 1989;
It works fine and pulls the expected results. Obviously, as I am using a form where the user is supposed to input the 'month' and 'year' themselves, this makes things a bit tricky.
What am I missing here? Cheers for any thoughts.
Note: the date_ordered field is a Date/Time field with a Short Date format.
This may help you..
Dim sql As String = "SELECT * FROM orders WHERE MONTH(date_ordered) = #mon and YEAR(date_ordered) = #year"
Using cn As New SqlConnection("Your connection string here"), _
cmd As New SqlCommand(sql, cn)
cmd.Parameters.Add("#mon", SqlDbType.VarChar, 50).Value = textBox1.text
cmd.Parameters.Add("#year", SqlDbType.VarChar, 50).Value = textBox2.text
Return cmd.ExecuteScalar().ToString()
End Using

Display full query in statement with parameters

I have some trouble to debugging my query in vb.net.
I just wanna get full query with value inside it. I use parameters to add value in my query.
This is my code:
'Select query
Dim stm As String = "SELECT *, FORMAT(NOW(),'DD-MM-YYYY HH:NN:SS') as waktu FROM [user] WHERE [username]=? AND [password]=? AND active=TRUE"
Dim cmd As OleDbCommand = New OleDbCommand(stm, db)
'Parameters
Using md5Hash As MD5 = MD5.Create()
Dim pwd As String = GetMd5Hash(md5Hash, Me.tx_password.Text)
cmd.Parameters.Add("p1", OleDbType.VarChar, 25).Value = Me.tx_username.Text
cmd.Parameters.Add("p2", OleDbType.VarChar, 32).Value = pwd
End Using
'Execute Query
MsgBox(stm)
Dim reader As OleDbDataReader = cmd.ExecuteReader(CommandBehavior.SingleRow)
With this code, I just get result like this:
SELECT *, FORMAT(NOW(),'DD-MM-YYYY HH:NN:SS') as waktu FROM [user]
WHERE [username]=? AND [password]=? AND active=TRUE
How to get result like this:
SELECT *, FORMAT(NOW(),'DD-MM-YYYY HH:NN:SS') as waktu FROM [user]
WHERE [username]='adminUser' AND [password]='adminPassword' AND active=TRUE
Parameters are not concatenated into the command, they are sent separately to the database. Otherwise there will be no difference between using a parameterized query and using a concatenated one. (see the answer to a similar question here.)
This means that in order to debug your queries you will have to work a little harder then if your sql was concatenated by the vb.net code.
If your database supports stored procedure I recommend you start using them instead of parameterized queries. You will probably gain performance, and it will be easier to debug.
If not, you can copy the query as is to the sql editor, and use one of the debugger options to get the values of the parameters and copy them one by one to the sql editor.
Place this code below you have added the parameters and you'll have in debugSQL the SQL statement which will be executed
Dim debugSQL As String = cmd.CommandText
For Each param As SqlParameter In cmd.Parameters
debugSQL = debugSQL.Replace(debugSQL.ParameterName, debugSQL.Value.ToString())
Next

SQL Update Column By Adding A Number To Current Int

Simple enough, I can't figure out how to add (that's +) an integer from a textbox to the integer in the SQL Field.
So for example, the SQL Field may have '10' in it and the textbox may have '5' in it. I want to add these numbers together to store '15' without having to download the SQL Table.
The textbox that contains the integer to be added to the SQL integer is tranamount.Text and the SQL Column in the SQL Table is #ugpoints. Please note, without the '+' - which is in the below code and is admittedly wrong- the value of tranamount.Text is added to the Table without an issue, but it simply replaces the original value; meaning the end result would be '5' in the SQL Field.
What would be the proper way to structure this? I've tried the below code, but that clearly doesn't work.
cmd = New SqlCommand("UPDATE PersonsA SET U_G_Studio=#ugpoints WHERE Members_ID=#recevierID", con)
cmd.Parameters.AddWithValue("#recevierID", tranmemberID.Text)
cmd.Parameters.AddWithValue("#ugpoints", + tranamount.Text) '<--- Value to add.
cmd.ExecuteNonQuery()
Newbies question I know, I'm new to SQL in vb.
You have to use the correct sql:
Dim sql = "UPDATE PersonsA SET U_G_Studio=U_G_Studio + #ugpoints WHERE Members_ID=#recevierID"
Also use the correct type with AddWithValue:
Using cmd = New SqlCommand(sql, con)
' use the using-statement to dispose everything that implements IDisposable, so also the connection '
cmd.Parameters.AddWithValue("#ugpoints", Int32.Parse(tranamount.Text))
' .... '
End Using
Take the current value of the U_G_Studio field, add the value of the parameter and reassign to U_G_Studio, but keep in mind that you need to pass the value as an integer because otherwise the AddWithValue will pass a string and you get conversion errors coming from the db.
cmd = New SqlCommand("UPDATE PersonsA SET U_G_Studio=U_G_Studio + #ugpoints " &
"WHERE Members_ID=#recevierID", con)
cmd.Parameters.AddWithValue("#recevierID", tranmemberID.Text)
cmd.Parameters.AddWithValue("#ugpoints", Convert.ToInt32(tranamount.Text))
cmd.ExecuteNonQuery()
The SQL you want is:
"UPDATE PersonsA SET U_G_Studio= (U_G_Studio + #ugpoints) " & _
"WHERE Members_ID=#recevierID"
what about
cmd.Parameters.AddWithValue("#ugpoints", (int)tranamount.Text)
....
cmd = New SqlCommand("UPDATE PersonsA SET U_G_Studio= SET U_G_Studio + #ugpoints WHERE Members_ID=#recevierID", con)
edit1: STEVE WAS FASTER!

sql error - missing a (;) at the end of sql statement

I'm trying to get this bit work but it keep saying that missing a (;) at the end of a SQL statement. Basically, this code will get filename of a picture and insert into photodatabase in fileName column, if the filename already exist then just update = 1.
INSERT INTO photoDB(fileNames)
VALUES('" + Path.GetFileName(fileName) + "')
ON DUPLICATE KEY UPDATE fileNames = 1
The error is message is quite clear. You need a semi-colon at the end of your SQL string (fileNames = 1;.
Here is an example that helps to protect against SQL injection and fixes your semi colon problem.
SqlConnection conn = new SqlConnection("ConnectionString");
SqlCommand command = new SqlCommand();
command.Connection = conn;
command.CommandText = "INSERT INTO photoDB (fileNames) VALUES(#fileName) ON DUPLICATE KEY UPDATE fileNames = 1;";
command.Parameters.Add(new SqlParameter("#filename", System.Data.SqlDbType.VarChar).Value = Path.GetFileName(fileName));
command.ExecuteNonQuery();
Second answer (now that the OP has fixed the semi-colon issue).
Is this MySQL? Other databases will not support that ON DUPLICATE KEY syntax.
Your ON DUPLICATE KEY clause sets a TEXT column (fileNames) to an INTEGER value (1). Try putting quotes around the integer value.

ASP.NET 2.0: Cannot Convert VarChar to Int

I have an ASP.Net form, where it grabs a value from a textbox:
<asp:TextBox ID="txtID" runat="server" maxlength=9></asp:TextBox>
The ID HAS to be 9 numbers.
After it grabs it, I want to insert it into a database (SQL Server 2005), so I build a parameterized string,
'The Query
cmd.CommandText = "insert into table (aid) values ('#aid')"
cmd.Connection = conn
'Grab the value
cmd.Parameters.add("#aid", SqlDBType.Int).value = txtID.text
'Execute!
cmd.Connection.Open()
cmd.ExecuteNonQuery
However, it doesn't let me. It keeps giving the following error message:
Conversion failed when converting the varchar value '#aid' to data type int.
So I've tried a variety of things:
cmd.Parameters.add("#aid", SqlDBType.Int).value = 999999999
cmd.Parameters.add("#aid", SqlDBType.Int).value = Convert.ToInt16(txtID.text)
cmd.Parameters.add("#aid", SqlDBType.Int).value = Convert.ToInt32(txtID.text)
cmd.Parameters.add("#aid", SqlDBType.Int).value = Convert.ToInt64(txtID.text)
Nothing works. Inside the database, the type is "int".
Any ideas?
Remove the quotes around #aid in your query, so that it looks like so:
cmd.CommandText = "insert into table (aid) values (#aid)"
Otherwise, you're sending the code mixed messages. Parameters are never enclosed in quotes. They are string literals if they're enclosed in quotes. Additionally, in pure SQL, numbers are not enclosed in quotes, but text values (varchar and the like) are. So, remove the quotes, and the parameter should have no issues being created.
Parameters aren't inserted straight into SQL wholesale. They're plopped in after SQL Server has parsed the query. Therefore, parameters should just be on their own, as they're taken as string literals if they aren't. The parameterization will take care to convert the parameter to the right data type for you. See this post for more on how parameters work behind the scenes.
Your sql query is the problem.
You are trying to do
INSERT INTO TABLE(aid) VALUES('123456789')
You need to drop the quotes and do
INSERT INTO TABLE(aid) VALUES(123456789)