好的,所以我试图从SQL中的数据库中获取18个“价格”,然后将其设置在本地数组中。到目前为止,我在数据检索中具有以下逻辑:

private void dbPrices()
{
    string myConnectionString;

    myConnectionString = "server=127.0.0.1;uid=root;" +
        "pwd=;database=phvpos";

    try
    {
        conn = new MySql.Data.MySqlClient.MySqlConnection();
        conn.ConnectionString = myConnectionString;
        conn.Open();
    }
    catch (MySql.Data.MySqlClient.MySqlException ex)
    {
        MessageBox.Show(ex.Message);
    }

    for (int i = 1; i < 19; i++)
    {
        MySqlCommand cmd = conn.CreateCommand();
        cmd.CommandText = "SELECT price from products where id = '" + i + "'";

        MySqlDataReader reader = cmd.ExecuteReader();

        while (reader.Read())
        {
            pr[i] = reader.ToString();
            prods[i] = int.Parse(pr[i]);
        }
    }
}


获得总金额的逻辑如下:

private void btnTotal_Click(object sender, EventArgs e)
{
    dbPrices();

    itemcost[0] = Convert.ToInt32(txtRice.Text) * prods[0];
    itemcost[1] = Convert.ToInt32(txtAdobo.Text) * prods[1];
    itemcost[2] = Convert.ToInt32(txtIgado.Text) * prods[2];
    itemcost[3] = Convert.ToInt32(txtSisig.Text) * prods[3];
    ...
    itemcost[18] = itemcost[0] + itemcost[1] + itemcost[2] + itemcost[3] + itemcost[4] + itemcost[5]
        + itemcost[6] + itemcost[7] + itemcost[8] + itemcost[9] + itemcost[10]
        + itemcost[11] + itemcost[12] + itemcost[13] + itemcost[14] + itemcost[15]
        + itemcost[16] + itemcost[17];

    int totalPrice = itemcost[18];

    lblTotal.Text = Convert.ToString(totalPrice);
}


dbPrices()中的此行吐出“输入字符串的格式不正确”错误:

while (reader.Read())
{
    pr[i] = reader.ToString();
    prods[i] = int.Parse(pr[i]);
}


我也尝试过:

while (reader.Read())
{
    prods[i] = Convert.toInt32(reader.ToString());
}


而且还会吐出同样的错误。我做错了什么吗?

最佳答案

结果的值需要转换为int,并且for循环块将来可能会导致严重的问题,您可能需要进行投影查询,然后分配结果的值。

MySqlCommand cmd = conn.CreateCommand();
cmd.CommandText = $"SELECT price FROM products WHERE id BETWEEN 1 AND 18"; //use projection. if you have a dynamic product id set, you can use IN in query.
MySqlDataReader reader = cmd.ExecuteReader();
var counter = 0; //counter
while (reader.Read())
{
    prods[counter] = Convert.ToInt32(reader["price"]); //convert the result first then assign it to the item.
    counter++;
}

10-04 17:54