Insert the date into table - asp.net

I am trying to get From date and To date in two text boxes using the calender control and then trying to insert this value in a table. How can I proceed with this??
Please help..
string comstr = "insert into ATM_DETAILS_TB values(" + txtpin.Text + ",'" + Convert.ToDateTime(txtvldfrm.Text) + "','" + Convert.ToDateTime(txtvldto.Text) + "'," + Convert.ToInt32(ddlaccno.SelectedValue) + ",'" + Session["strUid"].ToString() + "')";
while using this code it shows error like "String was not recognized as a valid DateTime"
what should I do??

Use Validation controls to validate that the values in textbox values are valid dates.
Your code us contencating strings directly from user input. This opens you up to all sorts of nasty attacks, the primary being SQL Injection. Use parameterized queries instead.

Always use DateTime.TryParse or TryParseExact method to parse the date.
DateTime vldDate;
bool isValid=false;
if(DateTime.TryParse(txtvldfrm.Text,out vldDate))
{
isValid=true;
}
....
if(isValid)
{
command.Parametter.Add("#vldto",SqlDbType.DateTime).Value=vldDate;
command.Parametter.Add("#strUid",SqlDbType.VarChar,30).Value=Session["strUid"];
.....
}

You Use from parameterized queries like this:
string comstr = "insert into ATM_DETAILS_TB values(#pin,#vldfrm,#vldto,#ddlaccno,#strUid)";
YourCommand.Parametter.AddWithValue("#vldto",Convert.ToDateTime(txtvldto.Text));
YourCommand.Parametter.AddWithValue("#strUid",Session["strUid"].ToString());
....Define the Other Paraametter
Edit----
check this question String was not rec...

Related

Conversion of varchar into datetime data type

This is in Microsoft SQL Server Management Studio; I have a column Order_Date in my table, and the data type is datetime.
In my ASP.NET web application, I am inserting the date using this query:
"INSERT INTO Order (ORDER_DATE) VALUES ('" + System.DateTime.Now + "')";
I've done the same thing before in another project but didn't get error there. Here I'm getting error when try to insert data. How can I solve this error?
System.DateTime.Now will automatically be converted to a string by C# when it is appended to your INSERT string. However the string it produces will be dependent on the regional/culture settings on the box on which it is executing. It is exceptionally unlikely to produce a datetime string format that SQL understands. So you need to ensure that the correct format is used by explicitly setting it when the string is generated:
"INSERT INTO Order (ORDER_DATE) Values ('" + System.DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff") + "')";
You could just make it a SqlType like:
"INSERT INTO Order (ORDER_DATE) Values ('" + new System.Data.SqlTypes.SqlDateTime(DateTime.Now).ToString() + "');"
Check out:
https://learn.microsoft.com/en-us/dotnet/api/system.data.sqltypes.sqldatetime

Sqlite insert gives syntax error

I am working on flex actionscript project. In which i am going to save/insert records in sqlite database, which i got in response.
But, form that records some records are not inserted into table. When i catch the error it gives sql error.
near '/': syntax error
In response i have got whole html markup.
I have written/execute query inside for loop like:
var insert:SQLStatement = new SQLStatement();
insert.sqlConnection = sqlConnectionSync;
insert.text = 'INSERT OR IGNORE INTO TableName (MessageID, AccountID, Body) VALUES ("' + listArray[i].MessageID + '","' + listArray[i].AccountID + '","' + listArray[i].Body + '")';
insert.execute();
I have also tried changing " in place of ' and vice versa.
But it gives other error of '
Error #3115: SQL Error.
near 'll': syntax error
And
near '_blank': syntax error
Any help would greatly appreciated.
To avoid such problem, you can use SQLStatement.parameters property like this, for example :
var insert:SQLStatement = new SQLStatement();
insert.text = 'INSERT OR IGNORE INTO TableName (MessageID, AccountID, Body) VALUES (:param1, :param2, :param3)';
insert.parameters[':param1'] = listArray[i].MessageID;
insert.parameters[':param2'] = listArray[i].AccountID;
insert.parameters[':param3'] = listArray[i].Body;
insert.execute();
Hope that can help.
Posting the full query as text would help but most likely you have " or ' characters in your data (like ...="_blank" or "You'll"). You'd need to escape your variable values before inserting them into the database. I have switched " and ' from your example:
insert.text = "INSERT OR IGNORE INTO TableName (MessageID, AccountID, Body) VALUES ('" + escapeChars(listArray[i].MessageID) + "','" + escapeChars(listArray[i].AccountID) + "','" + escapeChars(listArray[i].Body) + "')";
private function escapeChars(myString:String):String
{
// Since we are using "'" we'd need to escape all other "'" characters
return myString.replace(/'/gi, "\'");
}

Where condition in LinqDataSource for string in ASP.NET

I am trying to populate data in gridview by using LinqDataSource and in the where condition of LinqDataSource1 - programmatically I am not sure about the syntax on how to pass a string value to a particular column?
What is the syntax for where condition in LinqDataSource on a string programmatically?
I am familiar with the one in int:
int id = 5;
for example:
LinqDataSource1.Where = "ID =" +id;
But, not sure about the syntax for string.
Please suggest something!
Ok, finally I got the syntax for string in LinqDataSource:
LinqDataSource1.Where = "Title.Contains("+ "\"" + txtTitle.Text + "\""+ ")";

How to make value of a column name appear with single apostrophe in sql statement of sql helper inside asp. net

SQLHelper sqhlpr = new SQLHelper();
sqhlpr.SqlText = "Select StudentName from tblStudentInfo where class=" + NurseryButton.Text;
DataTable dt = sqhlpr.getDataTable(false);
This is my code.Now the result of sqhlpr.sqlText is
select StudentName from tblStudentInfo where class= **Nursery**
(i.e.NurseryButton.Text=Nursery) but the result that i want is select StudentName from tblStudentInfo where class= 'Nursery'.How can this be done??? This looks simple but I can't just figure it out...
"Select StudentName from tblStudentInfo where class='" + NurseryButton.Text + "'";
But you definitively should not use it that way! (SQL Injection)
Here is a good answer: Sql inline query with parameters. Parameter is not read when the query is executed
Your query is a string. You do:
result = "somestring" + someVariable;
Now you want to enclose someVariable in sinlge quotes, which is done like this:
result = "somestring" + "'" + someVariable + "'";
Or shorter:
result = "somestring'" + someVariable + "'";
However is is worth noting that manually building queries is quite "not done". You should look at tools like parameterized queries or even O/R mappers like Entity Framework.
The following code will do what you want:
SQLHelper sqhlpr = new SQLHelper();
sqhlpr.SqlText = "Select StudentName from tblStudentInfo where class = '" + NurseryButton.Text + "'";
DataTable dt = sqhlpr.getDataTable(false);
You need to think about two more things though:
What happens if someone puts an apostrophe in the NurseryButton.Text somehow
Will SQLHelper protect you from this sort of thing, or do you need to do it yourself
You should consider parametrized querying or stored procedures in some way to make sure that your input to the database is done safely.

Asp.net add to database

Is it possible to add from a single textbox to different tables in a database.
I have a addclub webform and i would like to add clubname to a number of different tables.
The following is my current code that i have.
cmd = new SqlCommand("insert into youthclublist(youthclubname, description, address1, address2, county, postcode, email, phone) values ('" + youthclubname.Text + "', '" + description.Text + "','" + address1.Text + "','" + address2.Text + "', '" + county.Text + "', '" + postcode.Text + "', '" + email.Text + "', '" + phone.Text + "')", connection);
It is possible yes but consider my point below:
Think about normal form, it should be possible to design the database so that you only need to alter it on one place. If you have to change the name in several places it is likely not following normal form and the database could be redesigned.
The way you are doing the update is not advisable, have a look into SQLInjection attacks as the above code is vulnerable to this. Using parameters in the SQLCommand rather than creating a big string is a better way to do this from a security and performance point.
Hope I have not been too negative
Andy
You can do it if you use a transaction (and you should use parameters to get around some SQL injection attack problems) like so (this means that all the inserts are done in a single block on the database which is safer than doing them one after the other):
using (var cmd = new SqlCommand("BEGIN TRANSACTION;"
+ "INSERT INTO youthclublist(youthclubname) VALUES (#youthclubname);"
// Add all your INSERT statements here for the other tables in a similar way to above (I simplified it to show just one column, but you get the idea)
+ "COMMIT;", conn))
{
// Add your parameters - one for each of your text boxes
cmd.Parameters.Add("#youthclubname", SqlDbType.NVarChar).Value = youthclubname.Text;
// execute the transaction
cmd.ExecuteNonQuery();
}

Resources