【发布时间】:2014-02-24 13:55:53
【问题描述】:
我正在尝试将一个简单的行列表从 DataGridView 插入到数据库中。
我已经创建了一个checkedbox,在检查后,该项目将被添加到DataGridView。现在我正在尝试做 INSERT 部分。这是我到目前为止提出的:
try
{
string strAppointment = "SELECT appointmentID FROM APPOINTMENT WHERE appointmentID=@searchappointmentID";
SqlCommand cmdAppointment = new SqlCommand(strAppointment, connection);
cmdAppointment.Parameters.AddWithValue("@searchappointmentID", txtAppointmentID.Text);
connection.Open();
for (int i = 0; i < dataPrescription.Rows.Count; i++)
{
string firstColumn = dataPrescription[0, dataPrescription.CurrentCell.RowIndex].Value.ToString();
string strMedications = "SELECT medicationID FROM MEDICATION WHERE medicationName= ('" + firstColumn + "')";
SqlCommand cmdMedications = new SqlCommand(strMedications, connection);
SqlDataReader readMedications = cmdMedications.ExecuteReader();
if (readMedications.Read())
{
string getDrugID = readMedications["medicationID"].ToString();
string strPrescriptions = "INSERT INTO PRESCRIPTION (appointmentID, medicationID, quantity) " +
"VALUES (@insertAppointment, "
+ getDrugID + ", "
+ dataPrescription.Rows[i].Cells["columnQuantity"].Value + ");";
SqlCommand cmdPrescriptions = new SqlCommand(strPrescriptions, connection);
cmdPrescriptions.Parameters.AddWithValue("@insertAppointment", txtAppointmentID.Text);
prescriptionsResult = cmdAppointment.ExecuteNonQuery();
}
readMedications.Close();
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Error");
}
finally
{
connection.Close();
}
现在它给了我这个错误:“已经有一个打开的 DataReader 与必须先关闭的命令关联”。我不知道我做错了什么
【问题讨论】:
标签: c# sql winforms datagridview