【问题标题】:Insert list of rows插入行列表
【发布时间】: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


    【解决方案1】:

    试试这个:(初始化数据读取器)

    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();
    

    【讨论】:

    • 那你可以用博士做什么?
    【解决方案2】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-01-12
      • 1970-01-01
      • 1970-01-01
      • 2020-09-08
      • 2022-01-27
      • 1970-01-01
      • 2020-11-09
      相关资源
      最近更新 更多