Click here to Skip to main content
Rate this: bad
good
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 9:35am
Comments
Sandeep Mewara at 15-Jul-10 15:43pm
   
What error? What format?
Member 7217874 at 15-Jul-10 15:52pm
   
showing Incorrect Syntax error near 12.
12 is the hours.
OriginalGriff at 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 at 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)



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