So I was just searching how to do an "INSERT INTO" query and found this:
sql="INSERT INTO Customers (ID,firstName,"
sql=sql & "lastName)"
sql=sql & " VALUES "
sql=sql & "('" & Request.Form("id") & "',"
sql=sql & "'" & Request.Form("firstname") & "',"
sql=sql & "'" & Request.Form("lastname") & "')"
I know it works but I want to make it a single query without all the sql=sql's
You took the route of a quick hack as stated in your comments by doing rhis:
sql="INSERT INTO Customers (ID,firstName,lastName) VALUES ('" & Request.Form("id") & "','" & Request.Form("fistname") & "','" & Request.Form("lastname") & "')"
Let me persist in stating that to prevent several issues (sql injection being one of them) you could leverage the use of paramterized queries.
I assume you have an ADO command somewhere after your sql statement. It is much safer if you use command parameters to send parameters from the website to the query.
command.CommandText = "INSERT INTO Customers (ID,firstName,lastName) VALUES (?,?,?)"
Set param = command.CreateParameter ("id", adInteger, adParamInput)
param.value = Request.Form("id")
command.Parameters.Append param
Set param2 = command.CreateParameter ("firstname", adVarWChar, adParamInput, 50)
param2.value = Request.Form("firstname")
command.Parameters.Append param2
Set param3 = command.CreateParameter ("lastname", adVarWChar, adParamInput, 50)
param3.value = Request.Form("lastname")
command.Parameters.Append param3
command.Execute
Have a look at Command Object Parameters for more background.
You can do like this:
string sql = string.Format("INSERT INTO Customers(Id,FirstName,LastName) VALUES({0},'{1}','{2}')", param0, param1, param2);
It Works! But be careful this way have SQL Injection issues.
Related
Try
con.Open()
comm.Connection = con
comm.CommandText = "insert into [adminanduser] (username,firstname,lastname,email,password,usertype) values ('" & TextBox1.Text & "','" & TextBox2.Text & "','" & TextBox3.Text & "','" & TextBox4.Text & "','" & TextBox5.Text & "','" & Label6.Text & "')"
comm.ExecuteNonQuery()
Response.Write("Data Successfully Saved")
con.Close()
Catch
Finally
End Try
Unless you alter the table such that there is a unqiue constraint on one of the columns, you will not be able to get an exception when inserting duplicate data. Rather than attempting to generate an error though, you could always use SQL to ensure that a duplicate entry won't be added. Presuming you are trying to keep unique usernames, you could always write your SQL like this:
comm.CommandText = #"IF NOT EXISTS(SELECT * FROM [adminanduser] WHERE [username] = #username)
INSERT INTO [adminanduser] SELECT #username,#firstname,#lastname,#email,#password,#usertype";
comm.Parameters.AddWithValue("#username", TextBox1.Text);
comm.Parameters.AddWithValue("#firstname", TextBox2.Text);
comm.Parameters.AddWithValue("#lastname", TextBox3.Text);
comm.Parameters.AddWithValue("#email", TextBox4.Text);
comm.Parameters.AddWithValue("#password", TextBox5.Text);
comm.Parameters.AddWithValue("#usertype", TextBox6.Text);
If you would rather go down the road of generating the error, try
ALTER TABLE [adminanduser]
ADD UNIQUE (username)
That should throw an exception the next time you attempt to insert a duplicate username
I am getting this Error
Incorrect syntax near the keyword 'user'.
con.Open()
comm.Connection = con
comm.CommandText = "insert into user (username,firstname,lastname,email,password) values ('" & TextBox1.Text & "','" & TextBox2.Text & "','" & TextBox3.Text & "','" & TextBox4.Text & "','" & TextBox5.Text & "')"
comm.ExecuteNonQuery()
Response.Write("Data Successfully Saved")
User is reserve key word, so use it like this
"insert into [user]
You need to use square brackets around user as it's a keyword.
By the way, this type of query is vulnerable to SQL injection attacks. (Think about what you can put into your text boxes to drop the entire users table, or how you could convert the first few names and passwords into an e-mail address for the user you're inserting.) You should use parameterised queries instead or stored procedures.
I have a section of code in one of my scripts that is getting an error in its syntax.
if(status <> true and Request.QueryString("selectId") = "undefined") then
strConn ="PROVIDER=foobar;Server=foo;Database=foo;Uid=bar;Pwd=bar;"
Set cnt = Server.CreateObject("ADODB.Connection")
set rs1 = CreateObject("ADODB.Recordset")
rs1.CursorLocation = adUseClient
cnt.ConnectionString= strConn
cnt.Open strConn
sql="Select * from rule1 where skucode='" & Request.Form("txthidden") & "' and letter1id ='" & Request.Form("lrt1") & "' and letter2id ='" & Request.Form("Select1") & "' and letter3id ='" & Request.Form("Select2") & "'"
rs1.Open sql,cnt,2,2
if not rs1.EOF then
Response.write("<script language=""javascript"">alert('Rules already exists!');</script>")
else
sql="INSERT INTO rule1 (letter1id,letter2id,letter3id,HTML,skucode) VALUES "
sql=sql & "('" & Request.Form("lrt1") & "',"
sql=sql & "'" & Request.Form("Select1") & "',"
sql=sql & "'" & Request.Form("Select2") & "',"
sql=sql & "'" & Request.Form("txthtml") & "',"
sql=sql & "'" & Request.Form("txthidden") & "')"
cnt.Execute sql
Response.write("<script language=""javascript"">alert('Rules Added successfully!');window.location='" & "viewrule1.asp?skucodes=" & Request.Form("txthidden") & "';</script>")
end if
rs1.Close
cnt.close
The error message I get is:
Microsoft OLE DB Provider for SQL Server error '80040e14'
Incorrect syntax near the keyword 'close'.
/path/file.asp, line 75
Instead of closing it, you can detach it completely:
set cnt = Nothing
There shouldn't be a problem. All i think is if your data is too long or not. Sometimes it occurs when your row limit exceeds. SQL Server 6.5 allows a maximum row size of 1962 bytes and SQL Server 7.0 allows a maximum row size of 8060 bytes. Its just an assumption
Presuming it's the last line that's throwing the error, I'd replace it with:
If IsObject(cnt) Then
On Error Resume Next
If cnt.State = 1 Then ' 1 = adStateOpen '
cnt.Close
End If
Set cnt = Nothing
Err.Clear
On Error Goto 0
End If
cnt is probably already closed by the time it reaches that portion of your script which is why it's throwing the error. Checking its status before closing it needs to be wrapped in On Error Resume Next logic, otherwise it'll throw another error.
I am trying to excute this sql query
Dim str As String = "UPDATE table1 SET " & _
"number = '" & strc & "'," & _
"code = '" & "123" & "'," & _
"line= '" & dd1.text & "'," & _
"sellr = '" & txtrun.text & "'," & _
"endu= '" & txtex1.value+txtex2.value & "'" & _
"WHERE number IN (select table1.number" & _
"FROM table1 INNER JOIN table2 ON table1.number = table2.number" & _
"WHERE ((table1.username)='" & session("username") & "' AND (table1.pass)='" & session("pass") & "' AND (table2.sellnum)='" & session("sellnum") & "'));"
there is a Syntax error in query expression and this is te first time I am using nested subquery
all the field are getting String values
So if someone can tell me what is the right approach to write this query I will be very grateful
You're missing spaces after table1.number and table2.number fields in the subquery.
I don't know where you're using this query, but you might want to read about SQL injection. When you stick strings together to build SQL, your code may be vulnerable to malicious users who put SQL code into the fields of your application.
When inserting data into a database, the following error occurs
"Excepted end of statement"
sqlstr = "INSERT INTO tblContact (Email,FirstName,LastName,Comments) VALUES ('" & Email & "', '" & First Name & "','" & Last Name & "','" & Comments & "')"
objConn.Execute sqlstr
Try using single-word identifiers for your first-name and last-name variables:
sqlstr = "INSERT INTO tblContact (Email,FirstName,LastName,Comments) " & _
" VALUES ('" & Email & "', '" & FirstName & "','" & LastName & "','" & Comments & "')"
objConn.Execute sqlstr
Assuming you've got variables with those names in your VBScript, that'll solve your current problem with Expected end of statement.
Your second problem is your code's vulnerability to SQL injection.
To help fix that problem, see:
Classic ASP SQL Injection Protection
http://www.stardeveloper.com/articles/display.html?article=2008112501&page=1
You might have single quote in one of the values, resulting in invalid SQL. You have to escape single quotes, though better rewrite your code to use parameters instead.
sqlstr = "INSERT INTO tblContact (Email, FirstName, LastName, Comments) " & _
" VALUES ('" & Replace(Email, "'", "''") & "', '" & Replace(FirstName, "'", "''") & "', '" & Replace(LastName, "'", "''") & "', '" & Replace(Comments, "'", "''") & "')"
objConn.Execute sqlstr