如何使用c#在sql server中插入日期数据类型 [英] How to insert date data type in sql server using c#

查看:483
本文介绍了如何使用c#在sql server中插入日期数据类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的桌子



My table

create table monthcal
(
Id int primary key identity (1,1),
StartDate date,
EndDate date
)





.cs




.cs

SqlCommand cmd = new SqlCommand("Insert into  monthcal values (@NoOfMonths,@StartDate,@EndDate)", con);
        cmd.Parameters.AddWithValue("@NoOfMonths", txtNoOfMonths.Text.ToString());
        cmd.Parameters.AddWithValue("@StartDate", txtStartDate.Text.ToString());
        cmd.Parameters.AddWithValue("@EndDate", txtEndDate.Text.ToString());
        con.Open();
        cmd.ExecuteNonQuery();

    }





收到错误



只有在使用列列表并且IDENTITY_INSERT为ON时,才能指定表'monthcal'中标识列的显式值。



am getting an error

An explicit value for the identity column in table 'monthcal' can only be specified when a column list is used and IDENTITY_INSERT is ON.

推荐答案

当你问这个时上次:如何计算月数到开始日期并显示在结束日期 [ ^ ]

我告诉你不要传递字符串,而是将它们转换为适当的值:

When you asked this last time: How to calculate months to start date and display in end date[^]
I told you not to pass strings, but to convert them to appropriate values:
int months;
if (!int.Parse(txtNoOfMonths.Text, out months))
   {
   // Report problem with number!
   return;
   }
DateTime startDate;
if (!DateTime.Parse(txtStartDate.Text, out startDate))
   {
   // Report problem with Date!
   return;
   }



并使用转换后的值代替字符串值直接传递给SQL。



这样做吧!



当你在它时,改变你的INSERT命令:


And use the converted values instead of string values to pass directly to SQL.

So do it!

And while you are at it, change your INSERT command:

SqlCommand cmd = new SqlCommand("INSERT INTO monthcal (Startdate, EndDate) VALUES (@StartDate,@EndDate)", con);
cmd.Parameters.AddWithValue("@StartDate", startDate);
cmd.Parameters.AddWithValue("@EndDate", endDate);
con.Open();
cmd.ExecuteNonQuery();



因为如果你没有列出列,它会尝试插入以列顺序开头的值 - 所以SQL会尝试将您的第一个参数放入IDENTITY字段,该字段永远不会起作用,并且总是会抛出异常。



请尝试Dispose SqlConnection和SqlCommand对象 - 一个使用块是最简单的方法......


Because if you don't list the columns, it will try to insert the values starting in column order - so SQL will try to put your first parameter into the IDENTITY field, which will never work and will always throw an exception.

And please, do try to Dispose SqlConnection and SqlCommand objects - a using block is the easiest way...


这篇关于如何使用c#在sql server中插入日期数据类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆