简体   繁体   中英

Error when saving datetime to a SQL Server database

I'm doing a bit of C# Winforms coding in my spare time, just getting to grips with everything. I have a SQL script which creates a local db on vs2012 as follows:

-- Creating table 'Users'--
CREATE TABLE [dbo].[Users]
(
    [UserID] int IDENTITY(1,1) NOT NULL,
    [Surname] nvarchar(30)  NOT NULL,
    [Forename] nvarchar(30)  NOT NULL,
    [Company] nvarchar (30) NOT NULL,
    [SecurityLevel] int NOT NULL,
    [IssueDate] DateTime  NOT NULL,
    [ExpiryDate] DateTime  NOT NULL,
    [CardID] int NOT NULL,
);
GO

Now I want to save details to that table, so I created a method:

  private void btnSaveDetails_Click(object sender, EventArgs e)
  {
        SqlConnection sc = new SqlConnection();
        SqlCommand com = new SqlCommand();
        sc.ConnectionString = (Properties.Settings.Default.BioEngineering);
        sc.Open();
        com.Connection = sc;
        com.CommandText = ("INSERT INTO Users (Forename, Surname, Company, SecurityLevel, IssueDate, ExpiryDate, CardID) VALUES ('" + this.txtFirstName.Text + "','" + this.txtLastName.Text + "','" + this.txtCompany.Text + "','" + this.cboSecurityLevel.Text + "','" + this.dtpIssueDate.Value + "','" + this.dtpExpiryDate.Value + "','" + this.cboCardID.Text + "');");

        com.ExecuteNonQuery();
        sc.Close();
    }

When I run the code I get an error

The conversion of a varchar data type to a datetime data type resulted in an out-of-range value

I know it has something to do with the datetime format of either the SQL or C# equivalent but I don't know how to format the datetime in order to comply to the error. Any ideas? I tried formatting it withing the Command Text line but it didn't seem to resolve the issue.

Datepicker.Value is returned as

[Your_System_Short_Date_Format] + [Space] + [Your_System_Long_Time_Format]

I don't know why in this format but just found when checked with the Default Long Format while adding the DateTimePicker.

So you are passing a value depending upon you system [Regional/Calendar] settings where the SQL engine expects to be in a format like EBrown said

yyyy-MM-dd HH:mm:ss.fffffff

So if you surely want to Concatenate then you can use like

 command.CommandText = 
    "INSERT INTO EMPLOYEES(DateOfBirth) VALUES ('" +
     dtpDateOfBirth.Value.ToString("yyyy-MM-dd HH:mm:ss") + "')";

But i truly recommend you to keep a practice of using parameters from the beginning itself. Or else after making a huge application, you might need to walk back to change those concatenations to Parameters.

It is simple like

command.CommandText = "INSERT INTO EMPLOYEES(DateOfBirth) VALUES (@dob)";

command.Parameters.Add("@dob", SqlDbType.DateTime).Value = dtpDateOfBirth.Value;

     // Or Simply

command.Parameters.AddWithValue("@dob", dtpDateOfBirth.Value);

You can add more parameters with different Data Types using parameters. The SqlCommand class safely converts those to an SqlCommand especially from Injection Attacks.

First of all, the way you did is very crude way of running sql statements that is prone to lots of errors, memory leaks, sql injection attacks, and security issues.

--You should use using statement to dispose connection & command objects, better error handling.

-- you should use parameterized queries or stored procs or ORMs like nhibernate or EF.

Anyway error in your code is as follows

convert date fields to this format .ToString("MM/dd/YYYY")

 private void btnSaveDetails_Click(object sender, EventArgs e)
    {
        SqlConnection sc = new SqlConnection();
        SqlCommand com = new SqlCommand();
        sc.ConnectionString = (Properties.Settings.Default.BioEngineering);
        sc.Open();
        com.Connection = sc;
        com.CommandText = ("INSERT INTO Users (Forename, Surname, Company, SecurityLevel, IssueDate, ExpiryDate, CardID) VALUES ('" + this.txtFirstName.Text + "','" + this.txtLastName.Text + "','" + this.txtCompany.Text + "','" + this.cboSecurityLevel.Text + "','" + this.dtpIssueDate.Value.ToString("MM/dd/YYYY") + "','" + this.dtpExpiryDate.Value.ToString("MM/dd/YYYY") + "','" + this.cboCardID.Text + "');");

        com.ExecuteNonQuery();
        sc.Close();
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM