Click here to Skip to main content
12,246,406 members (40,545 online)
Rate this:
 
Please Sign up or sign in to vote.
See more: ASP.NET
Hi,

I am inserting datetime from C# to SqlServer. But format is not compatible.

I tried using DateTime.Now. But it is giving error.

Please help?
Posted 15-Jul-10 10:35am
Comments
Sandeep Mewara 15-Jul-10 15:43pm
   
What error? What format?
Member 7217874 15-Jul-10 15:52pm
   
showing Incorrect Syntax error near 12.
12 is the hours.
OriginalGriff 16-Jul-10 4:25am
   
Answer updated.
Rate this: bad
 
good
Please Sign up or sign in to vote.

Solution 1

Insert it with a parametrised query, and it will sort itself out - as well as being safer (see SQL Injection attack). Google SQLCommand.AddWithValue and use that instead of including the DateTime.Now in your SQL command string.

Member 7217874 wrote:
Can you give an example with entering more than one parameter insertion takes place.


SqlConnection conn = new SqlConnection("your connection string");
SqlCommand cmd = new SqlCommand("INSERT INTO table_name (username, logindate) VALUES (@USERNAME, @DATE)", conn);
cmd.Parameters.AddWithValue("@USERNAME", tbUserName.Text);
cmd.Parameters.AddWithValue("@DATE", DateTime.Now);
int i = cmd.ExecuteNonQuery();
  Permalink  
v2
Comments
Member 7217874 15-Jul-10 15:59pm
   
Can you give an example with entering more than one parameter insertion takes place.
Rate this: bad
 
good
Please Sign up or sign in to vote.

Solution 3

ok try this
................
Sql
.............
abc datetime ,.......
abc is a columns
,......... ............
C#
......................

private void button1_Click(object sender, EventArgs e)
        {
            try
            {
                string a = DateTime.Now.ToShortDateString();
                string Query = "Insert into ab values('" + a + "')";
                string con = "Data source =abc; initial catalog=ex;            integrated security= true";
                SqlConnection cn = new SqlConnection(con);
                cn.Open();
                SqlCommand cmd = new SqlCommand( Query ,cn);
                cmd.ExecuteNonQuery();
               
            }
            catch (Exception g)
            {
                label1.Text = g.Message;
            }
        }
  Permalink  
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

  Print Answers RSS
Top Experts
Last 24hrsThis month


Advertise | Privacy | Mobile
Web02 | 2.8.160426.1 | Last Updated 24 Jan 2013
Copyright © CodeProject, 1999-2016
All Rights Reserved. Terms of Service
Layout: fixed | fluid

CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100