0

我正在尝试从 Customer 表中检索“customer_id”并将其插入

fare_tariff(tariff_id, customer_id, total_price)

所以我从 Customer 表中检索 customer_id,如下所示:

using (SqlCommand command = new SqlCommand("SELECT customer_id FROM Customer WHERE UserName = '" + username + "' Password = '"+password +"' ", connection))
{
    string cust_id = customer_id.ToString();
    SqlDataReader myReader = command.ExecuteReader();

    if (myReader.Read())
    {
        cust_id = myReader["customer_id"].ToString();
    }

    int c_id = Convert.ToInt32(cust_id);

    myReader.Close();
    custID(c_id);
}

并将 customer_id 插入到 fare_tariff 表中,如下所示:

using (SqlCommand command = new SqlCommand("INSERT INTO flight_reservation(tariff_id, customer_id, total_price) VALUES(@val1,@val2,@val3)", connection))
{

    command.Parameters.Add("@val1", SqlDbType.Int).Value = tariff_id;
    command.Parameters.Add("@val2", SqlDbType.Int).Value = customer_id;
    command.Parameters.Add("@val3", SqlDbType.VarChar).Value = total_price.ToString();

    command.ExecuteNonQuery();
}  

我将customer_id 声明为用于存储customer_id 的变量。

问题是:关税 ID 和总价格已成功插入,但客户 ID 列仍为空。

需要帮助。

4

1 回答 1

0

向客户端获取数据并逐行返回服务器会产生很大的开销。有更好的方法来做同样的事情,所谓的“插入/选择”查询:

  using (SqlCommand command = connection.CreateCommand()) {
    command.CommandText =
      "insert into Flight_Reservation(\n" +
      "            Customer_Id,\n" +
      "            Tariff_Id,\n" +
      "            Total_Price)\n" +
      "     select Customer_Id,\n" +
      "            @prm_Tariff_Id,\n" +
      "            @prm_Total_Price\n" +
      "       from Customer\n" +
      "      where (UserName = @prm_UserName)\n" + 
      "            (Password = @prm_Password)"; 

    command.Parameters.Add("@prm_Tariff_Id", SqlDbType.VarChar, 80).Value = tariff_id;
    command.Parameters.Add("@prm_Total_Price", SqlDbType.VarChar, 80).Value = total_price.ToString();
    command.Parameters.Add("@prm_UserName", SqlDbType.VarChar, 80).Value = username;
    command.Parameters.Add("@prm_Password", SqlDbType.VarChar, 80).Value = password;

    command.ExecuteNonQuery();
  }
于 2013-04-27T15:48:30.210 回答