简体   繁体   中英

SQL query result to variable?

I usually do this in VB and its much easier, this is my first time in C# and I can't figure it out. I'm just wanting to read a row, check that it has rows, and assign the number that exist in that column to StockQuan

    public int StockQuan;
    public int NewAmount;

    public const string ConnectionStringToORACLE = "Provider=OraOLEDB.Oracle.1;Data Source=Souarce;User ID=user;Password=pass;";
    public OleDbDataReader rowread;

    public OleDbDataReader Read_quan(string txtPartNo, int txtAmount)
    {
        var conn = new OleDbConnection(ConnectionStringToORACLE);
        conn.Open();

        string query = "select QUANTITY_IN_STOCK from MPCS.SHOP_INV_STOCK where SI_KEY = ? AND LOCATION = ?";
        var cmd = new OleDbCommand(query, conn);

        cmd.Parameters.AddWithValue("SI_KEY", txtPartNo);
        cmd.Parameters.AddWithValue("LOCATION", "HQ-TC");

        //rowread = cmd.ExecuteReader();
        //rowread.Read();
        //if (rowread.HasRows)
        //{
            //while (rowread.Read())
            //{
                StockQuan = (int)cmd.ExecuteScalar();
            //}
            NewAmount = StockQuan - txtAmount;

        //}
        //else
        //{
        //    MessageBox.Show("Error reading quantity. Check with Administrator", "Error", MessageBoxButton.OK, MessageBoxImage.Warning);
        //}
        return rowread;
    }

I commented out most things to just simplify where I'm going wrong and now the error is invalid cast on (int)cmd.ExecuteScalar();

试试以下

 StockQuan = Convert.ToInt32(cmd.ExecuteScalar());

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM