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?
Well, the immediate problem with your code is that you haven't called company_reader2.Read()
to move the cursor onto the first row.
From the docs for SqlDataReader.Read
:
The default position of the SqlDataReader is before the first record. Therefore, you must call Read to begin accessing any data.
You should also note the return value of Read()
which indicates whether or not you've read to the end of the record set.
Other problems:
- You should put
using
statements around theSqlCommand
andSqlDataReader
, otherwise if there's an exception you won't be closing the connection. You may be able to get away with disposing the command and letting the reader just disappear automatically - but I typically dispose of both just so I don't need to think too carefully. - You're assuming that the format of date/time will be appropriate by just calling
ToString
with no format specifier. - You should use a parameterised SQL query to avoid SQL injection attacks.
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();
}
精彩评论