加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

使用C#将DateTime插入SQL Server

发布时间:2020-12-16 00:01:38 所属栏目:百科 来源:网络整理
导读:参见英文答案 How can I add user-supplied input to an SQL statement?????????????????????????????????????2个 我是C#ADO.NET和SQL的新手,有一个我无法想象的问题.我正在尝试使用C#将DateTime插入SQL Server.我收到了消息 “Conversion failed when conve
参见英文答案 > How can I add user-supplied input to an SQL statement?????????????????????????????????????2个
我是C#ADO.NET和SQL的新手,有一个我无法想象的问题.我正在尝试使用C#将DateTime插入SQL Server.我收到了消息

“Conversion failed when converting date/and or time from character
string”

当程序命中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,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();
            }
        }
}

解决方法

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

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

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

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读