string with 's not getting inserted with insert statement - asp.net

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.

Related

vb.net string concat adds vbCrlf literal to the string

I am trying to build a string that includes a newline character and is getting the weirdest result. This string is going to be stored in a SQL database to be later used as part of an email. My code is the following:
Dim strBody As String = "Andy," & Environment.NewLine
When I inspect the value of strBody during a debugging session, it is the following:
"Andy," & vbCrlf
I am obviously expecting is to be more like:
"Andy,"
Knowing that what is after the , is a hidden character.
Ultimately, the problem is... when I include strBody as part of my SQL insert statement, it literally shows up as the following within my SQL insert statement:
'Andy," & vbCrLf & "'
I was using this code yesterday and it worked fine. I am using similar code within another function of the same asp.net project and it works fine. I have tried using + instead of &, I have tried to use vbCrLf instead of Environment.NewLine, I have tried using stringbuilder, I have tried using string.concat. All with the same results where the & vbCrLf is included in strBody.
Is there a setting that I accidentally changed?
I know this is a weird one... Any help is greatly appreciated.
This is only Visual Studio showing you that there is new line character (vbCrLf or Environment.NewLine). If you use that string anywhere, it will be stored correctly.
I believe you will need to use some combination of Char(10) and Char(13):
Dim strBody As String = "'Andy,'" & " + CHAR(13)+CHAR(10) + "
There is a discussion about these and other methods on this thread.
You can do like this if you just need to insert Environment.NewLine inside database.
Dim a As String = """ & Environment.NewLine & """
Dim strBody As String = String.Format("Andy,{0}", a)
'"Andy," & Environment.NewLine & ""

Date changes to a vastly different value when saved into database

I'm trying to enter a date that's in a textbox into a column of datetime type
The code is as follows
txtbookissue_date.Text = DateTime.Now.Date
txtbookreturn_date.Text = DateAdd(DateInterval.Day, 7, DateTime.Now.Date)
When I Insert these two values into a database, (insert into book....) values such as 17-02-1984 show up in the database rather than, say, 26-2-2015.
I did a little research and found out that SQL interprets it as "26 minus 2 minus 2015" rather than as a date.
Printing Date(txtbookissue_date.Text) gives correct results, the only problem is saving it into the database.
The solution for this was apparently to enclose the date in single quotes, i.e '26-2-2015' rather than just 26-2-2015, Since I'm using a date function I decided to change
txtbookissue_date.Text = DateTime.Now.Date
to
txtbookissue_date.Text= "'"+DateTime.Now.Date+"'"
but It returns an error, something similar to 'cannot convert varchar type to date type, out of range exception'
How do I fix this? any help would be appreciated.
txtbookissue_date.Text = DateTime.Now.Date
txtbookreturn_date.Text = DateAdd(DateInterval.Day, 10, DateTime.Now.Date)
Protected Sub btn_issue_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btn_issue.Click
con.Open()
cmd.CommandText = "insert into Book (book_id, book_name, book_author,publisher,mem_id,mem_name,issue_date,return_date) values('" & txtbookissue_id.Text & "','" & txtibookssue_name.Text & "','" & txtbookissue_author.Text & "','" & txtbookissue_publi.Text & "','" & txtbookissue_memid.Text & "','" & txtbookissue_memname.Text & "'," & txtbookissue_date.Text & "," & txtbookreturn_date.Text & ")"
cmd.Connection = con
cmd.ExecuteNonQuery()
con.Close()
Response.Redirect("Welcome.aspx")
End Sub
you are inserting date as a text. I mean while you need to insert it '2015-02-26' you are trying to insert it with another format. In fact you should use parameters with your sql query. Your sql statement should be something like that
insert into Book (book_id, book_name, book_author,publisher,mem_id,mem_name,issue_date,return_date) values(#book_id, #book_name, #book_author,#publisher,#mem_id,#mem_name,#issue_date,#return_date)
Before executing query you should set parameters in command object.
cmd.Parameters.AddWithValue("#return_date", DateAdd(DateInterval.Day, 10, Date.Now.Date))
For more information about using parameters with access you can take a look here
First of all, I would highly suggest using Paramaters.
Second, since you want to format your date into a string that is not the default culture. I would suggest you use String.Format() or ToString() (examples).
Since your database most likely expects a datetime. You could parse the string back to a DateTime using DateTime.ParseExact. Look at this answer for a howto.
Let me know if this helps, if not you need to supply us with more info.
You are putting string in a DateTime column, please convert the values back to their original types before putting them in the database.
DateTime issueDate = DateTime.Parse(txtbookissue_date.Text);
DateTime returnDate = DateTime.Parse(txtbookreturn_date.Text);

convert an empty string (from textbox) to null using ASP.NET

if I don't enter anything in one of the textbox , ASP.NET can't tell an empty textbox and treat it at null... So anyone please help me how to detect an empty textbox and set that to null
i know that this code is ganna work well
If MUSIC_TITLE.Text.Trim() = "" Then
MUSIC_TITLE.Text = Nothing
End If
but i can't use be couse i have a lot of forms in my application so i need somthing or any function exist in the ASP.NET that can handel this
and thats for the insert in a requet the sql server
"insert into Reunion values(" & Convert.ToInt32(ID_Reunion.Text) & ",'" & d.ToString("MM/dd/yyyy") & "'," & Convert.ToInt32(ID_Membre.Text) & ",'" & Type_Reunion.Text & "','" & Session("Nom_GIAC") & "')"
and tnks
This sounds like you're trying to directly store the textbox values in your database.
Please don't do this. If you haven't already, learn about the high risk security threat of SQL Injection and parameterize your INSERTS and UPDATES.
Before setting the parameters, you can convert empty strings to Nothing if required.
Dim musicTitle as String = _
If(String.IsNullOrWhiteSpace(MUSIC_TITLE.Text), Nothing, MUSIC_TITLE.Text)
In your insert sp should be like:
create procedure Insert(#test varchar(50)=NULL)
as
begin
update foo set testCol=#test
end
In c#, use below code, when calling the sp and adding the parameters:
if(txt.Text!=String.Empty)
{
cmd.Parameters.Add("#test",SqlDBType.Varchar,20).Value=txt.Text;
}

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

Login and syntax error

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.

Resources