Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Wanet Telecoms Ltd on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

How to write Current Date and ime to DB? 2

Status
Not open for further replies.

passs

Programmer
Dec 29, 2003
170
RU
Hello everybody!

Does somebody know how to write Date and Time to Db? This column in Db Tbale has datetime type. And I always get an error trying to write such way:
"INSERT INTO Table (dtCreated) VALUES ("+System.DateTime.Now+")"

What is the problem?
Thank you!
Best regards,
Alex
 
use the SQL function getdate() as below

"INSERT INTO Table (dtCreated) VALUES (getdate())
 
Easy way (which leaves you open to a SQL Injection attack):
Code:
"INSERT INTO Table (dtCreated) VALUES ('" + System.DateTime.Now.ToString() + "')"

Correct way:
Code:
Dim sb As StringBuilder

sb = New StringBuilder()

sb.Append("INSERT INTO Table (dtCreated)")
sb.Append("  VALUES(?)"

Dim myCommand As SqlCommand
myCommand = New SqlCommand(sb.ToString(), myConnection)

myCommand.Parameters.Add("dtCreated", SqlDbType.DateTime).Value = DateTime.Now

myCommand.ExecuteNonQuery()

Chip H.


____________________________________________________________________
If you want to get the best response to a question, please read FAQ222-2244 first
 
Chip-
can you explain how this leaves you open to a sql injection attack? Sorry looking for some education here.. =)
 
Take a look at this for a walkthrough.

But basically, whenever you use string concatenation to build up arguments for a SQL statement, you're vulnerable to someone adding statements which do bad things. Anything from examining your DB schema, to inserting false data, to formatting the drive using one of the SQL Server extended stored procedures.

Chip H.


____________________________________________________________________
If you want to get the best response to a question, please read FAQ222-2244 first
 
Thank you all!

Now it is working! I used getdate()!
Thanks thanks thanks thanks!!!!

Best regards,
Alex
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top