C#MySqlConnector在同一连接中的下一个查询
本文关键字:下一个 查询 连接 C#MySqlConnector | 更新日期: 2023-09-27 18:27:57
我有以下代码:
string myConnection = "server=localhost;database=test;uid=test;password=test";
string query = "SELECT label_type, label, quantity FROM system_printserver WHERE print=0";
try
{
MySqlConnection myConn = new MySqlConnection(myConnection);
myConn.Open();
MySqlCommand command = new MySqlCommand(query, myConn);
MySqlDataAdapter adapter = new MySqlDataAdapter(command);
DataTable data = new DataTable();
adapter.Fill(data);
dataGridView1.DataSource = data;
printDocument1.PrintPage += new PrintPageEventHandler(printDocument1_PrintPage);
MySqlDataReader myReader;
myReader = command.ExecuteReader();
while (myReader.Read()) {
orderNumber = myReader.GetString(1);
myReader.Close();
string queryOrder = "SELECT id_order, id_carrier FROM ps_orders WHERE id_order=28329";
MySqlCommand commandOrder = new MySqlCommand(queryOrder, myConn);
MySqlDataReader myReaderOrder;
myReaderOrder = commandOrder.ExecuteReader();
idCarrier = myReaderOrder.GetString(1);
printDocument1.Print();
}
我遇到了一个问题,因为第二个查询字符串queryOrder不起作用。查询正常,但变量"idCarrier"不接受任何值。
当一个读卡器已经打开并正在处理记录时,我不认为您可以将另一个读写器连接到一个连接。您必须首先检索所有记录,即ToList()或Dataset,或者为第二个读取器使用辅助连接。
为了让你的生活更轻松,可以考虑使用Dapper或Linq2Db,这两个很棒的微ORM。
这样试试:
using(var connection = new MySqlConnection("server=localhost;database=test;uid=test;password=test") {
connection.Open();
int orderNumber = 0;
using (var command = connection.CreateCommand()) {
command.CommandText = @"SELECT label_type, label, quantity FROM system_printserver WHERE print=0";
DataTable data = new DataTable();
adapter.Fill(data);
dataGridView1.DataSource = data;
var reader = command.ExecuteReader();
printDocument1.PrintPage += new PrintPageEventHandler(printDocument1_PrintPage);
if(reader.Read()) {
orderNumber = Convert.ToInt32(reader.GetString(1));
}
}
using(var command = connection.CreateCommand()) {
command.CommandText = string.format(@"SELECT id_order, id_carrier FROM ps_orders WHERE id_order={0}",orderNumber);
var reader = command.ExecuteReader();
if(reader.Read()){
printDocument1.Print();
return reader.GetString(1);
}
}
}