What is wrong with this code asp.net using vb - asp.net

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.

Related

how can i try and catch duplicate data in the database

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

insert into syntax error

Private databaseConnector As DatabaseConnector
Dim fulltxtSQL As String
DatabaseConnector = New DatabaseConnector
Try
fulltxtSQL = "insert into [user-table] (username, password) VALUES ('" & UserName.Text & "','" & Password.Text & "')"
DatabaseConnector.RunSqlNonQuery(fulltxtSQL)
If DatabaseConnector.RunSqlNonQuery(fulltxtSQL) = True Then
MsgBox("thank you for registering ", vbInformation, Title.Trim)
Response.Redirect("Default.aspx")
Exit Sub
Else
MsgBox(MsgBox("There has been a error in your registering", vbInformation, Title.Trim))
End If
Catch ex As Exception
MsgBox(ex.Message.Trim, MsgBoxStyle.Information + MsgBoxStyle.OkOnly, Me.Title.Trim)
Exit Sub
End Try
End Sub
am trying to get the data from textbox to the database table.
syntax error in insert into statement the connection to the database works fine but when it reaches the insert into statement i get the error
Try this
INSERT INTO [user-table] ([username],[password]) VALUES('" & UserName.Text & "','" & Password.Text & "')"
You query contains special character such as user,table and password so it will give error. So what you need to do is to put such characters in paranthesis [].
Also you should use parameterized query.
try using this command
cmd = New System.Data.OleDb.OleDbCommand("INSERT INTO [user-table] ([username],[password]) VALUES('" & UserName.Text & "','" & Password.Text & "')", con)
if your table name contains such special charaters then use square brackets.

No data exists for row/column

While executing the following code in ASP.NET with VB, I am getting the error "No data exists for the row/column."
Dim hdnuserid = e.CommandArgument
If e.CommandName = "additem" Then
' First, see if the product is already in the vendor_catalog table
Dim dr, dr2, username
dr = connection.returnsqlresult("SELECT * FROM vendor_users where vendor_id = '" & Request("vendor_id") & "' AND userid = '" & hdnuserid & "'")
If dr.hasrows() Then
dr.read()
Response.Write("<script type=""text/javascript"">alert(""User already assigned to this vendor."");</script>")
Else
dr2 = connection.returnsqlresult("SELECT * FROM users WHERE userid = '" & hdnuserid & "'")
Response.Write(hdnuserid)
If dr2.hasrows() Then
dr2.read()
username = dr("username")
connection.executesql("INSERT INTO vendor_users(userid, vendor_id, username) VALUES('" & hdnuserid & "','" & Request("vendor_id") & "','" & username & "')")
'ScriptManager.RegisterStartupScript(Me, GetType(Page), "itemsadded", "window.opener.__doPostBack('__Page', 'populate_usergrid');window.close();", True)
Else
Response.Write("<script type=""text/javascript"">alert(""User does not exist."");</script>")
End If
dr2.close()
End If
dr.close()
Else
End If
I have checked that the columns exist in my tables, and also checked the select * from users statement in SQL directly with a hard coded value and I see the result I expect. I'm not sure why I am getting this error. The error is being thrown on the username = dr("username") line.
Any assistance in this would be very helpful.
JV
I think you have a bit of a typo. Change
username = dr("username")
to
username = dr2("username")
Shouldnt the reader object be dr2 instead of dr? since dr doesnt have any rows, dr("username") wouldnt be accessible.
username = dr2("username")

Can someone make this a single query?

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.

How can I insert uploaded images into a database?

I want to insert uploaded image in root directory images folder and its path to image column in database.
I am using the following code. It inserts the path to images in the database column, but not the filename:
Protected Sub Button3_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button3.Click
On Error Resume Next
If FileUpload1.HasFile Then
FileUpload1.SaveAs(IO.Path.Combine(Server.MapPath("images"), FileUpload1.FileName))
End If
'/// upload images
Dim con As New SqlConnection
Dim cmd As New SqlCommand
con.ConnectionString = "Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\Database.mdf;Integrated Security=True;User Instance=True"
con.Open()
cmd.Connection = con
cmd.CommandText = "INSERT INTO Table3 (city, hotel, location, avialiability, room, price, image, category, from1, to1, price1, from2, to2, price2, from3, to3, price3, details) VALUES('" & Trim(DropDownList1.SelectedItem.Text) & "','" & Trim(DropDownList2.SelectedItem.Text) & "','" & Trim(TextBox5.Text) & "','" & Trim(TextBox6.Text) & "','" & Trim(DropDownList3.SelectedItem.Text) & "','" & Trim(TextBox7.Text) & "','" & "images/" & FileUpload1.FileName & "','" & Trim(TextBox17.Text) & "','" & Trim(TextBox8.Text) & "','" & Trim(TextBox9.Text) & "','" & Trim(TextBox10.Text) & "','" & Trim(TextBox11.Text) & "','" & Trim(TextBox12.Text) & "','" & Trim(TextBox13.Text) & "','" & Trim(TextBox14.Text) & "','" & Trim(TextBox15.Text) & "','" & Trim(TextBox16.Text) & "','" & (Editor1.Content) & "')"
cmd.ExecuteNonQuery()
con.Close()
End Sub
Try this:
Dim cmd As MySqlCommand = Nothing
Try
Dim query As String = "INSERT INTO (city, hotel, location) VALUES (#city, #hotel, #location)"
cmd = New MySqlCommand(query, connection)
cmd.Parameters.AddWithValue("#city", ddlCity.SelectedItem.Text)
cmd.Parameters.AddWithValue("#title", txtTitle.Text)
cmd.Parameters.AddWithValue("#location", txtLocation.Text)
cmd.ExecuteNonQuery()
Catch ex As Exception
Messagebox.Show("Error: " & ex.Message, MsgBoxStyle.Critical)
End Try
There are several important things to remember here:
Use Naming Conventions and Meaningful Names for your components. Such as txtCity for a TextBox that holds City data. You'll avoid confusion this way.
Use Parameterized Query when building your SQL CommandText next time and always avoid using string concatenation. This saves you lot of time and headache (also for us ;D). By doing so, you can easily change the values in the query. Also when you use string concatenation to build query strings, you'll encounter problems when your values have special characters but by using SQL Parameters this will be avoided.
It inserts the path to images in the database column, but not the filename.
You can try checking the source for the filename value by setting a breakpoint in that part of the code so you can follow and check it.
Hope this helps.
Try this:
''//cmd.ExecuteNonQuery() Comment out for now.
Response.Write(cmnd.CommandText)
Take a look at the commandText and if you can figure out the problem. If part of the Insert statement works its probably a simple SQL syntax error which you should be able to pick up visually. If you still can't see the problem post your code here.
Incidentally, building up your SQL command strings like this is only going to cause headaches. Try using a Parameterised Query in future - it'll go a long way to securing your application from real-world SQL Injection attacks and save hours of your life ;-)
HTH

Resources