表架构:
CREATE TABLE [dbo].[Sales_main](
[Receipt_no] [decimal](18, 0) NOT NULL,
[Receipt_Date] [datetime] NOT NULL,
[Receipt_Time] [datetime] NOT NULL,
[User_id] [nvarchar](255) NOT NULL,
[Total_amt] [float] NOT NULL,
[Discount] [float] NOT NULL,
[To_pay] [float] NOT NULL,
[Paid] [float] NOT NULL,
[Balance] [float] NOT NULL,
[roundoff_amount] [float] NOT NULL,
[CreatedID] [varchar](50) NULL,
[CreatedDateTime] [smalldatetime] NULL,
[UpdatedID] [varchar](50) NULL,
[UpdatedDateTime] [smalldatetime] NULL)
我的sql查询看起来像这样
sql = "insert into Sales_main(Receipt_no,Receipt_Date,Receipt_Time,User_id,Total_amt,Discount,To_pay,Paid,Balance,roundoff_amount,CreatedID,CreatedDateTime) values(" + bosales.Receipt_no + ",'" + bosales.Receipt_Date.ToString("dd-MMM-yyyy") + "','" + bosales.Receipt_Time.ToString("t") + "','" + bosales.User_id + "'," + bosales.Total_amt + "," + bosales.Discount_amt + "," + bosales.Amt_tobe_paid + "," + bosales.Amt_paid + "," + bosales.Balance + "," + bosales.Roundoff + ",'" + bosales.Createdid + "','" + bosales.Createddate.ToString("dd-MMM-yyyy") + "')";
此查询的输出为:
43 |27/01/2015 12:00:00 AM |01/01/1900 5:00:00 PM |admin |20 |0 |20 |20 |0 |0 |admin |27/01/2015 12:00:00 AM |NULL |NULL
我想要插入时间值(下午5:00:00)而不是01/01/1900 5:00:00 PM。
请帮帮我。
答案 0 :(得分:0)
嗯,我认为你做错了什么。
用它的字符串表示形式插入你的日期时间值是一个坏主意。
您正在使用"t"
standard format specifier之类的;
bosales.Receipt_Time.ToString("t")
不要这样做!阅读:Bad habits to kick : choosing the wrong data type
SQL Server有time
type,它定义了一天的时间。 MySQL也有TIME
Type。
.NET Framework的DateTime
有TimeOfDay
property,它将当前实例的时间作为TimeSpan
返回。
然后您可以将值插入;
bosales.Receipt_Time.TimeOfDay
到您的time
类型列。
而且,您应该始终使用parameterized queries。这种字符串连接对SQL Injection攻击开放。
注意:看起来您使用的是SQL Server 2005,而且此版本没有time
类型。您可以阅读如何将其转换为datetime
:Time DataType in Sql Server 2005