栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

从日期时间到字符串格式的转换错误

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

从日期时间到字符串格式的转换错误

Okey,您的代码有一些问题。我将尝试按顺序解释所有这些内容。

首先,如果您使用

DateTime
带有字符串连接的值(在
+
运算符上),
.ToString
则将自动为它们调用方法,并且您可能会为数据库列生成“正确的”文本。千万
不能 选择错误的数据类型的列
。您需要 直接*
传递您的
DateTime
价值。如果您不知道自己知道哪个SqlDbType作为值,则还可以读取Mapping
CLR参数数据。
*

正如评论中所建议的那样,解决这种情况的最佳方法是使用参数化查询。另一方面,这些字符串连接对SQL注入攻击开放。

也可以使用

using
语句来自动处理连接(我们看不到,但是..)和命令,而不是手动调用
.Dispose
方法(您没有看到)。

举个例子;

public void insertBooking(int bookingID, int customerID, int entertainmentID,    DateTime bookingDate, int numberOfGuests, double price,    bool deposit, decimal depositPrice){    using (var con = new SqlConnection(yourConnectionString))    using (var cmd = con.CreateCommand())    {        cmd.CommandText = @"INSERT INTO Booking (bookingID, customerID, entertainmentID,       [Booking Date], [Number Of Guests], [Price], [Deposit?],       [Deposit Price]) Values(@bookId, @cusId, @entId, @bookdate, @guests, @price, @deposit, @depositPrice)";        cmd.Parameters.Add("@bookId", SqlDbType.Int).Value = bookingID;        cmd.Parameters.Add("@cusId", SqlDbType.Int).Value = customerID;        cmd.Parameters.Add("@entId", SqlDbType.Int).Value = entertainmentID;        cmd.Parameters.Add("@bookdate", SqlDbType.DateTime).Value = bookingDate;        cmd.Parameters.Add("@guests", SqlDbType.Int).Value = numberOfGuests;        cmd.Parameters.Add("@price", SqlDbType.Decimal).Value = price;        cmd.Parameters.Add("@deposit", SqlDbType.Bit).Value = deposit;        cmd.Parameters.Add("@depositPrice", SqlDbType.Decimal).Value = depositPrice;        con.Open();        cmd.ExecuteNonQuery();    }}


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/374807.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号