【问题标题】:Insert DateTime into SQL Server using C# [duplicate]使用 C# 将 DateTime 插入 SQL Server [重复]
【发布时间】:2011-12-08 06:05:38
【问题描述】:

我是 C# ADO.NET 和 SQL 的新手,遇到了一个我无法解决的问题。我正在尝试使用 C# 将 DateTime 插入到 SQL Server 中。我收到消息

“从字符转换日期/和/或时间时转换失败 字符串”

当程序到达cmd.ExecuteNonQuery(); 行时。对此的任何帮助都非常感谢

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using AutoLotConnectedLayer;
using System.Configuration;
using System.Data;

namespace AutoLotCUIClient
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("***** The AutoLot Console UI *****\n");

            // Get connection string from App.config.
            string cnStr =
              ConfigurationManager.ConnectionStrings["AutoLotSqlProvider"].ConnectionString;
            //bool userDone = false;
            //string userCommand = "";

            // Create our InventoryDAL object.
            InventoryDAL invDAL = new InventoryDAL();
            invDAL.OpenConnection(cnStr);

            InsertNewCar(invDAL);

 #region Insert car
        private static void InsertNewCar(InventoryDAL invDAL)
        {
            // First get the user data.
            int newCarID;
            string newCarColor, newCarMake, newCarPetName;
            DateTime newDateOne;


            Console.Write("Enter Car ID: ");
            newCarID = int.Parse(Console.ReadLine());
            Console.Write("Enter Car Color: ");
            newCarColor = Console.ReadLine();
            Console.Write("Enter Car Make: ");
            newCarMake = Console.ReadLine();
            Console.Write("Enter Pet Name: ");
            newCarPetName = Console.ReadLine();
            Console.Write("Enter Date: ");

            newDateOne = DateTime.Parse(Console.ReadLine());

            // Now pass to data access library.
            // invDAL.InsertAuto(newCarID, newCarColor, newCarMake, newCarPetName);
            NewCar c = new NewCar
            {
                CarID = newCarID,
                Color = newCarColor,
                Make = newCarMake,
                PetName = newCarPetName,
                DateOne = newDateOne
            };
            invDAL.InsertAuto(c);
        }
        #endregion

DLL Being Used

using System;
using System.Collections.Generic;
using System.Text;

// We will make use of the SQL server
// provider; however, it would also be
// permissible to make use of the ADO.NET
// factory pattern for greater flexibility.
using System.Data;
using System.Data.SqlClient;

namespace AutoLotConnectedLayer
{
    public class NewCar
    {
        public int CarID { get; set; }
        public string Color { get; set; }
        public string Make { get; set; }
        public string PetName { get; set; }
        public DateTime DateOne { get; set; }
    }

    public class InventoryDAL
    {
        // This member will be used by all methods.
        private SqlConnection sqlCn = null; 

        #region Open / Close methods
        public void OpenConnection(string connectionString)
        {
            sqlCn = new SqlConnection();
            sqlCn.ConnectionString = connectionString;
            sqlCn.Open();
        }

        public void CloseConnection()


        {
            sqlCn.Close();
        }
        #endregion

        #region Insert method (no param-query)
        public void InsertAuto(NewCar car)
        {
            // Format and execute SQL statement.
            string sql = string.Format("Insert Into Inventory" +
              "(CarID, Make, Color, PetName, DateOne) Values" +
              "('{0}', '{1}', '{2}', '{3}', '{4}')", car.CarID, car.Make, car.Color, car.PetName, Convert.ToDateTime(car.DateOne) );

            // Execute using our connection.
            using (SqlCommand cmd = new SqlCommand(sql, this.sqlCn))
            {

               cmd.ExecuteNonQuery();
            }
        }
}

【问题讨论】:

  • DateOne 已经是 DateTime,您应该使用 paramerters 而不是字符串格式
  • 您必须在C#中使用DateTime.Now将日期和时间插入到数据库中的DATETIME

标签: c#


【解决方案1】:

不要使用动态 SQL,而是使用参数。

string sql = string.Format("Insert Into Inventory" +
          "(CarID, Make, Color, PetName, DateOne) Values" +
          "(@CarID,...

cmd.Parameters.AddWithValue("@CarID", car.CarID);
//...

这将防止 SQL 注入并允许更好的 SQL 优化。

【讨论】:

  • +1 用于使用参数而不是连接在一起的 SQL 命令!
【解决方案2】:

不要使用 String.Format 来组合一个巨大的字符串,而是使用参数化查询。

cmd.CommandText = 
    "Insert Into Inventory (CarID, Make, Color, PetName, DateOne) Values" +
          "(@carId, @make, @color, @petName, @dateOne)";

cmd.Parameters.AddWithValue("@carId", car.CarID);
cmd.Parameters.AddWithValue("@make", car.Make);
cmd.Parameters.AddWithValue("@color", car.Color);
cmd.Parameters.AddWithValue("@petName", car.PetName);
cmd.Parameters.AddWithValue("@dateOne", car.DateOne);

除了避免 awkard 字符串连接的需要之外,这还可以防止 Sql Injection 攻击。用你以前的方式,想象一下如果有人输入'); drop table cars; -- 来输入你的新车品牌会发生什么——或者如果有人只想让他们的汽车的宠物名字成为O'LearyMobile

【讨论】:

  • +1 用于使用参数而不是连接在一起的 SQL 命令!
【解决方案3】:

永远不要使用hard-coded SQL 语句。使用Stored-ProcedurePrepare(参数)查询。

试试这个,

 string sql = "Insert Into Inventory (CarID, Make, Color, PetName, DateOne)
                 Vaules (@CarID, @Make, @Color, @PetName, @DateOne)";

  using (SqlCommand cmd = new SqlCommand(sql, this.sqlCn))
  {
     cmd.Parameters.Add("@CarID",SqlDbType.Int).Value=car.CarID;
     cmd.Parameters.Add("@Make",SqlDbType.VarChar,20).Value=car.Make;
     cmd.Parameters.Add("@Color",SqlDbType.VarChar,20).Value=car.Color;
     cmd.Parameters.Add("@PetName",SqlDbType.VarChar,20).Value=car.PetName;
     cmd.Parameters.Add("@DateOne",SqlDbType.DateTime).Value=car.DateOne;
     cmd.ExecuteNonQuery();
   }

【讨论】:

  • +1 用于使用参数而不是连接在一起的 SQL 命令!
  • 非常感谢,太棒了
【解决方案4】:

当控制台询问日期时,您必须以 MM/DD/YYYY 格式输入日期

【讨论】:

    【解决方案5】:

    你可以使用 .Value.ToShortDateString()

    例如... 您将在 sql 上添加一个数据类型为 datetime 的日期, 在我下面的示例表中

    Create table dateTable
    (
    mydate datetime
    )
    connection.Open();
    SqlCommand cmd = new SqlCommand("INSERT INTO dateTable VALUES(" +dateTimePicker1.Value.ToShortDateString()+", con);
    
    cmd.ExecuteNonQuery();
    connection.Close();
    

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-07-21
    • 2011-08-30
    • 2013-04-02
    • 2017-08-26
    • 2014-03-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多