cd.Command.Text=“Select ans From a1 where num=‘“+textbox.text.Trim()+”’”; dr=cd.ExecuteReader();哪里有错误
时间: 2024-02-05 08:11:39 浏览: 71
这段代码缺少异常处理和数据库连接的打开和关闭操作。应该使用 try-catch-finally 块来处理异常,并在使用完 SqlDataReader 后关闭数据库连接和 DataReader。
以下是一个示例代码,供您参考:
```csharp
try
{
string connectionString = "your_connection_string_here";
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
string commandText = "SELECT ans FROM a1 WHERE num='" + textbox.Text.Trim() + "'";
using (SqlCommand command = new SqlCommand(commandText, connection))
{
using (SqlDataReader reader = command.ExecuteReader())
{
if (reader.Read())
{
string answer = reader.GetString(0);
// do something with the answer
}
else
{
// handle case where no answer was found
}
}
}
}
}
catch (Exception ex)
{
// handle exception here
}
finally
{
// make sure to close database connection and dispose of objects
}
```
阅读全文