从SQL数据库获取DateTime [英] Get DateTime from SQL database

查看:131
本文介绍了从SQL数据库获取DateTime的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在数据库的表中有一个DateTime记录,我写了一个查询来从数据库中获取它:

  string command2 =从Company_Data中选择Last_Modified,其中Company_Name =' + DescriptionEntryForm.SelectedItem.ToString()+'; 
SqlCommand search_company2 =新的SqlCommand(command2,con_string.con);
SqlDataReader company_reader2 = search_company2.ExecuteReader();
dateform.Text = company_reader2.GetValue(0).ToString();
company_reader2.Close();

但是倒数第二个语句抛出一个异常,指出在没有数据的情况下,无效的读取尝试。 / p>

我该如何解决?

解决方案

看起来像您

  company_reader2 = search_company2.ExecuteReader();已经执行了该命令,但实际上并未从中读取命令。 
if(company_reader2!= null&& company_reader2.HasRows){
company_reader2.Read();
dateform.Text = company_reader2 [0] .ToString();
}


I have a DateTime record in my table in a database and I write a query to get it from the database:

string command2 = "select Last_Modified from Company_Data where Company_Name='" + DescriptionEntryForm.SelectedItem.ToString() + "'";
SqlCommand search_company2 = new SqlCommand(command2, con_string.con);
SqlDataReader company_reader2 = search_company2.ExecuteReader();
dateform.Text = company_reader2.GetValue(0).ToString();
company_reader2.Close();

But the penultimate statement throw an exception saying "Invalid attempt to read when no data is present".

How can I solve it?

解决方案

It looks like you've executed the command, but haven't actually read from it.

company_reader2 = search_company2.ExecuteReader();
if (company_reader2 != null && company_reader2.HasRows) {
    company_reader2.Read();
    dateform.Text = company_reader2[0].ToString();
}

这篇关于从SQL数据库获取DateTime的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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