user3327117
user3327117

Reputation: 3

winform c# Error while inserting data (DateTime) into SQL

    SqlConnection con = new SqlConnection("Data Source=RANJEETMAURYA;Initial    Catalog=Project;Integrated Security=True");
    con.Open();

    DateTime current = DateTime.Now;

    //DateTime CurrentDate;
    //CurrentDate = Convert.ToDateTime(DateTime.Now.ToString("dd-MMM-yyyy"));
    current = Convert.ToDateTime(DateTime.Now.ToString("MM/dd/yyyy hh:mm"));

    SqlCommand cmd = new SqlCommand(@"INSERT INTO CustomerDetails
                      (Date, Name, Gender, Address, Contact_No, Email_ID)
VALUES        ('" +current+ "','" + txtName.Text + "','" + Gender + "','" +     txtAddress.Text + "','" + txtContact.Text + "','" + txtEmail.Text + "')", con);
    cmd.ExecuteNonQuery();
    con.Close();
    MessageBox.Show("Customer Information Added Successfully.", "Dairy  Management System", MessageBoxButtons.OK, MessageBoxIcon.Information);
    SQLFunctions.Refresh(this.dataGridCustomerDetails);

this is the error please help me out for what reason it is running some times, it is not running some times.

 System.FormatException was unhandled
  HResult=-2146233033
Message=String was not recognized as a valid DateTime.
Source=mscorlib
StackTrace:
   at System.DateTimeParse.Parse(String s, DateTimeFormatInfo dtfi, DateTimeStyles  styles)
   at System.Convert.ToDateTime(String value)
   at IndianDiary.frmCustomerDetails.btnAddNew_Click(Object sender, EventArgs e) in 

Upvotes: 0

Views: 641

Answers (3)

Sergey Berezovskiy
Sergey Berezovskiy

Reputation: 236208

You are converting current time to string and then parsing string back to DateTime:

DateTime current = DateTime.Now;
current = Convert.ToDateTime(DateTime.Now.ToString("MM/dd/yyyy hh:mm"));

What is the point of this? Just use DateTime.Now. Also use command parameters.

string sql = @"INSERT INTO CustomerDetails
               (Date, Name, Gender, Address, Contact_No, Email_ID)
               VALUES (@date, @name, @gender, @address, @contactNo, @emailId)";

SqlCommand cmd = new SqlCommand(sql, con);
cmd.Parameters.AddWithValue("@date", DateTime.Now);
cmd.Parameters.AddWithValue("@name", txtName.Text);
cmd.Parameters.AddWithValue("@gender", Gender);
cmd.Parameters.AddWithValue("@address", txtAddress.Text);
cmd.Parameters.AddWithValue("@contactNo", txtContact.Text);
cmd.Parameters.AddWithValue("@emailId", txtEmail.Text);

See How does SQLParameter prevent SQL Injection?


Also use App.config to store connection string:

<connectionStrings>
  <add name="ranjeet" 
       connectionString="Data Source=RANJEETMAURYA;Initial Catalog=Project;Integrated Security=True" 
       providerName="System.Data.EntityClient" />
</connectionStrings>

Then you will be able to get it with ConfigurationManager.


Also wrap connection and command into using statement to dispose them automatically:

using (SqlConnection con = new SqlConnection(connectionString))
using (SqlCommand cmd = new SqlCommand(sql, con))
{
    // add parameters
    con.Open();
    cmd.ExecuteNonQuery();
}

Upvotes: 4

Suraj Shrestha
Suraj Shrestha

Reputation: 1808

As Reference to the answer of Sergey Berezovskiy you can also pass the parameter as:

string sql = @"INSERT INTO CustomerDetails
               (Date, Name, Gender, Address, Contact_No, Email_ID)
               VALUES (@date, @name, @gender, @address, @contactNo, @emailId)";

SqlCommand cmd = new SqlCommand(sql);
cmd.Parameters.Add("@date", SqlDbType.Date).Value = DateTime.Now;
cmd.Parameters.Add("@name", SqlDbType.Varchar, 50).Value = txtName.Text;
cmd.Parameters.Add("@gender", SqlDbType.Varchar, 10).Value = Gender;
cmd.Parameters.Add("@address", SqlDbType.Varchar, 50).Value =txtAddress.Text;
cmd.Parameters.Add("@contactNo", SqlDbType.Varchar, 25).Value = txtContact.Text;
cmd.Parameters.Add("@emailId", SqlDbType.Varchar, 35).Value =txtEmail.Text;

Upvotes: 0

Rajeev Ranjan
Rajeev Ranjan

Reputation: 1036

Why are You converting it to string just send DateTime.Now to database and while retrieving it from database use this

retrievedDate= DateRetrieved.ToString("MM/dd/yyyy hh:mm");

Upvotes: 0

Related Questions