Date changes to a vastly different value when saved into database - asp.net

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);

Related

Separating values in a textbox by special character

I have an asp.net/vb.net web app that requires information to be put into a multiline text box. If the user hits enter while in the textbox it drops down to next line, and they can enter more data in. When it tries to go to the database it fails because of the way the data is represented. I need help with looping through the field and getting each value.
This is how the data is represented in the DataTable
0;0.123;0.234;0.345;...
I need each value between the ; character... so I was thinking something like this?
If dbRow.Item("PV").ToString.Contains(";") Then
For Each symbol As String In DBTable.Rows
'get data b/w the ';'
Next
End If
Any help would be greatly appreciated
Edit:
If dbRow.Item("PV").ToString.Contains(";") Then
For Each s As String In dbRow.Item("PV").ToString
Dim fields() As String = s.Split(";"c)
For Each value As String In fields
.Append("'" & CDbl(value) & "'," & "SysDate,1)")
DBCommand.CommandText = myInsertIntoProperty_DataStringBuilder.ToString
DBCommand.ExecuteNonQuery()
myInsertIntoPropertyStringBuilder = New StringBuilder
Next
Next
Else
.Append("'" & CDbl(dbRow.Item("PV")) & "'," & "SysDate,1)")
End If
You mean something like this?
Dim s As String In dbRow.Item("PV").ToString()
Dim fields() As String = s.Split(";"c)
For Each value As String In fields
' Do what you want with the value
Next
Then access each value with field(0), fields(1), etc. You can then convert it to the appropriate type, for example:
Dim value As Double = Double.Parse(fields(0), CultureInfo.InvariantCulture)

string with 's not getting inserted with insert statement

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.

Cant Insert date in mysql date attribute

I have a asp.net project where i have to get input from the user and insert it into date attribute in my database. but instead I have only 0000/00/00. I can't understand why.
the input comes from 3 text boxes. Than i concatenate them and pass it to the query. But something goes wrong. here is the code:
Bday = Month2.Text & "/" & Dates2.Text & "/" & years.Text
Dim StrQwery As String = "INSERT INTO account VALUES(accoint_id, '" & Bday &"')"
Dim smd As MySqlCommand = New MySqlCommand(stquery, myconn)
smd.ExecuteReader()
The same thing happens when I add time to the same string and want to pass it to the dateTime attribute. Can someone tell me what is wrong?
regTime = Month2.Text & "/" & Dates2.Text & "/" & years.Text & CStr(TimeValue(CStr(Now)))
Dim StrQwery As String = "INSERT INTO account VALUES(accoint_id, '" & regTime &"')"
Dim smd As MySqlCommand = New MySqlCommand(stquery, myconn)
smd.ExecuteReader()
MySQL's date-as-string format is yyyy-mm-hh and yyyy-mm-dd hh:mm:ss for datetime. If you insert anything else, like your xxxx/xx/xx, MySQl will not even TRY to guess what format it's in, and simply insert a 0000-00-00 to signal an invalid date.
This is not something you can change. Convert your dates to MySQL's standard format, or deal with the consequences.

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;
}

Conversion from string "ACECATN000001" to type 'Integer' is not valid

I am a new in using asp.net i have recieving an error of "Conversion from string "ACECATN000001" to type 'Integer' is not valid." can anyone help me how to solve this?? thanks in advance :D
If lbl_productcatcode.Text = "ACECATN000001" Then
txt_productcode.Text = Format(CInt(rdr.Item(0).ToString) + 1, "1000000")
End If
End If
cmd1.Connection.Close()
End Sub
You've posted some code but not said which line has the error, I presume it is this one:
cmd1.CommandText = "Select CategoryID from CategoryTable where ProductCategory = '" & DropDownList1.Text & "'"
If the CategoryId column on the CategoryTable is of type integer, then you cannot compare it against a string value. I would guess that you need to use the ID of the item bound to the DropdownList, IIRC there should be a SelectedValue property on the dropdown that you can use for this.
cmd1.CommandText = "Select CategoryID from CategoryTable where ProductCategory = " & DropDownList1.SelectedValue
Note the absense of single quotes as you will be injecting an int value into the sql statement.
Firstly: CInt(s) converts s(s being a string) to integer and is only valid if s contains only numbers(no letters).
In this line:
txt_productcode.Text = Format(CInt(rdr.Item(0).ToString) + 1, "1000000")
you are trying to convert rdr.Item(0).ToString to an integer. According to your code,
rdr.Item(0).ToString returns "ACECATN000001" which contains letters and hence cannot be converted to integer.
What exactly are u wanting to do in that line?

Resources