插入行列表

时间:2014-01-31 18:27:22

标签: c# sql winforms datagridview

我正在尝试从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必须先关闭”。我不知道我做错了什么

2 个答案:

答案 0 :(得分:2)

试试这个:(初始化datareader)

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 dr = new SqlDataReader(); //Insert this line in your code
            SqlDataReader readMedications = cmdMedications.ExecuteReader();

答案 1 :(得分:0)

看起来你正在尝试使用读取器占用的连接来执行命令,我会将其视为问题所在。不要尝试在阅读器中执行插入,而是尝试将数据读取到集合并关闭阅读器,然后迭代连接以使您进行更新。