我试图在一个简单的语句中从多个MySQL表中选择数据,但我的问题是当我尝试运行它时出现以下错误:
类型' System.Exception'的例外情况发生在MySql.Data.dll中但未在用户代码中处理
其他信息:数据阅读器中没有当前查询
我用来运行语句的代码如下:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace WebApplication1
{
public partial class RetrieveCars : System.Web.UI.Page
{
String Model;
MySql.Data.MySqlClient.MySqlConnection conn;
MySql.Data.MySqlClient.MySqlCommand cmd;
MySql.Data.MySqlClient.MySqlDataReader reader;
String queryStr;
protected void Page_Load(object sender, EventArgs e)
{
if (Request.QueryString["model_id"] != null)
{
Model = Request.QueryString["model_id"];
String connString = System.Configuration.ConfigurationManager.ConnectionStrings["WebAppConnString"].ToString();
conn = new MySql.Data.MySqlClient.MySqlConnection(connString);
conn.Open();
queryStr = "";
queryStr = "SELECT c.CarID, c.RegNumber, c.Colour , m.CarModel, m.CarMake, m.CostPerDay FROM car c INNER JOIN model m ON m.ModelID=c.ModelID WHERE c.ModelID = '" + Model + "'";
cmd = new MySql.Data.MySqlClient.MySqlCommand(queryStr, conn);
reader = cmd.ExecuteReader();
reader.Close();
conn.Close();
CarN.Text = reader.GetString(reader.GetOrdinal("CarModel"));
}
}
}
}
答案 0 :(得分:4)
在获取任何数据之前,您正在关闭阅读器和连接。只需将.Close()
次呼叫移至功能结束即可
您还需要在Read()
上调用reader
来实际获取一行数据。
cmd = new MySql.Data.MySqlClient.MySqlCommand(queryStr, conn);
reader = cmd.ExecuteReader();
// Read() will return a bool indicating whether a new row has been read
// false signals no more data
while (reader.Read()) {
// Do something with the row data
CarN.Text = reader.GetString(reader.GetOrdinal("CarModel"));
}
reader.Close();
conn.Close();