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
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.
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.
I am trying to insert a question in database with field in table as nvarchar(max) (sql server 2008 r2)
Code is as follows:
Protected Sub btnSave_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnSave.Click
gc.ExecuteCommand("insert into QuestionMaster values('" & txtQuestion.Text & "','" & ViewState("ClientID") & "','" & ViewState("KioskID") & "')")
Response.Write("<script type='text/javascript' language='javascript'>alert('Question Added Sucessfully!!!')</script>")
BindGrid()
End Sub
when i insert any string with :
what's your name?
then it gives me error:
Incorrect syntax near 's'. Unclosed quotation mark after the character string ')'.
If i simply supply string as:
What is your name?
Then it does not gives me error.
Please help me.
You should be using parameterised queries if possible since simple string insertion directly into a query will, as you have seen, possibly corrupt the query.
In other words, if the text box contains Paddy O'Rourke, your query becomes:
open close what the ?
| | |
insert into QuestionMaster values('Paddy O'Rourke') ...
and you can see the fact that the embedded ' is corrupting the query.
It will also, as you have yet to realise, allow people to perform SQL injection attacks on your database since you're not sanitising the input.
If, for some reason, your shop disallows parameterised queries (as it appears from one of your comments), find another place to work. No, just kidding, but in the presence of such a bone-headed policy, you'll need to sanitise the input yourself.
But that's fraught with danger, I would first try to change such a policy, laying out in no uncertain terms the risks involved.
Well, you should rather make use of Parameterized queries.
This will also avoid SQL Injection.
There may be a chance that your data may contain some special characters like single quotation mark which make your statement fail.
So better to use parameterized query: Parameterized queries do proper substitution of arguments prior to running the SQL query.
SqlCommand insertNewAreaPath = new SqlCommand(
"insert into QuestionMaster (Question, ClientID, KioskID) VALUES(#Question, #ClientID, #KioskID)", con);
insertNewAreaPath.Parameters.Add("#Question", txtQuestion.Text);
insertNewAreaPath.Parameters.Add("#ClientID", ViewState("ClientID"));
insertNewAreaPath.Parameters.Add("#KioskID", ViewState("KioskID"));
insertNewAreaPath.ExecuteNonQuery();
ELSE: use .Replace("'", "''")
gc.ExecuteCommand("insert into QuestionMaster values('" & txtQuestion.Text.Replace("'", "''") & "','" & ViewState("ClientID") & "','" & ViewState("KioskID") & "')")
You could escape single quote by replacing single quote (') with two single quotes ('') in the txtQuestion.Text.
Protected Sub btnSave_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnSave.Click
gc.ExecuteCommand("insert into QuestionMaster values('" & txtQuestion.Text.Replace("'", "''") & "','" & ViewState("ClientID") & "','" & ViewState("KioskID") & "')")
Response.Write("<script type='text/javascript' language='javascript'>alert('Question Added Sucessfully!!!')</script>")
BindGrid()
End Sub
Replace ' with '' and it will work fine.
Try this
what''s your name?
//declare this variable
String sql="insert into QuestionMaster values('" & txtQuestion.Text & "','" & ViewState("ClientID") & "','" & ViewState("KioskID") & "')";
debug it and you will find where it appears problem.
i try to do a login using asp.net 3.5 and sql server 2005 i create a dataset and do this code
but something is missing in the code here the code
Protected Sub btnlogin_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnlogin.Click
Dim LoginTable As New ClassSet.UsersDataTable
Dim LoginAdapter As New ClassSetTableAdapters.UsersTableAdapter
LoginAdapter.FillBylogin(LoginTable, txtuser.Text, txtpass.Text)
Dim dr As DataRow() = LoginTable.Select("Name= ' " & txtuser.Text & " 'Password= ' " & txtpass.Text & " '")
If dr.Length > 0 Then
Response.Redirect("MyClassifieds.aspx")
Else
Label1.Text = "Invalid UserName or Password"
End If
End Sub
it say that there is something missed after the password=' " & txtpass.Text in line 5 but i cant get what missed can any one help please
You are missing the "AND" statement between Name and Password
Dim dr As DataRow() = LoginTable.Select("Name= '" & txtuser.Text & "' AND Password= '" & txtpass.Text & "'")
You're missing an AND
Dim dr As DataRow() = LoginTable.Select("Name= '" & txtuser.Text & "' AND Password= '" & txtpass.Text & "'")
And I doubt you want spaces in there either.
But you also have a problem here, SQL Injection. You seriously do not want to build up dynamic SQL like this, you MUST parameterise all your queries.
Why are you running a select to verify the username and password in the login table when its just been filled using the username and password through the data adaptor? Surely you can just check its length then. Also, if there is any security in your login system the password won't be stored in plain text so the adaptors fill method should do some kind of one way hashing to find the correct password to return the the data table.