c# - 从 SQL 服务器获取 DateTime 并将其分配给属性
问题描述
我有以下课程:
public class Invoice
{
public int ID {get; set;}
public DateTime creationDate {get; set;}
}
我在我的 SQL-Server 数据库中保存了具有以下属性的发票:
invoice
- invoiceID [int, null]
- creationDate [datetime, null]
我的日期包含以下格式:2018-07-31 00:00:00.000
但是,当我收到带有以下内容的发票时
SqlCommand command = new SqlCommand(@"SELECT id, creationDate FROM invoice WHERE invoiceID = @invoiceID", conn);
command.Parameters.Add("@InvoiceID", SqlDbType.Int).Value = InvoiceID;
{
conn.Open();
SqlDataReader reader = command.ExecuteReader();
if (reader.Read())
{
temp.ID = int.Parse(reader["id"].ToString());
temp.InvoiceDate = Convert.ToDateTime(reader["creationDate"]).ToString("yyyy/MM/dd");
}
conn.Close();
}
但是,当我运行我的代码时,我得到了错误:
SqlDateTime 溢出。必须在 1753 年 1 月 1 日上午 12:00:00 到 9999 年 12 月 31 日晚上 11:59:59 之间
我究竟做错了什么?
解决方案
如果您有一个健全的数据库架构,则该createDate
列已经是一个 DateTime 值。转换字符串只会让你自己受伤。id
和相同int
。
using (var conn = new SqlConnection("connection string here"))
using (var command = new new SqlCommand(@"SELECT id, creationDate FROM invoice WHERE invoiceID = @invoiceID", conn))
{
command.Parameters.Add("@InvoiceID", SqlDbType.Int).Value = InvoiceID;
conn.Open();
SqlDataReader reader = command.ExecuteReader();
if (reader.Read())
{
temp.ID = (int)reader["id"];
temp.InvoiceDate = (DateTime)reader["creationDate"];
}
}
creationDate
如果can be ,您确实需要更加小心NULL
,但否则,简单的演员阵容就足够了。
推荐阅读
- multidimensional-array - Symfony 5/Twig:尽管密钥存在,但如何解决“数组的密钥不存在”?
- mount - 如何以可写权限在 samba 服务器中挂载共享目录?
- vue.js - Quasar exportFile utf-8 编码
- javascript - 过滤器方法内部的for循环无法按预期工作
- cuda - CUDA JIT 编译器是否执行设备链接时优化?
- azure - 如何以编程方式设置存储帐户访问密钥以在密钥保管库中自动轮换?
- python - 如何在sklearn逻辑回归中使用tanh而不是sigmoid
- python - 如何在另一个python文件中访问一个python文件中的函数变量
- java - RESTEasy:从 MongoDB 获取产品列表
- excel - 对于每个循环?