Home > database >  How to update the database with new information
How to update the database with new information

Time:11-29

Good morning, I'm trying to make an ATM, I'm having a problem, I do not know how to save in the database the new information I'm entering.

decimal deposit = 0;
Console.WriteLine("\n Quanto deseja depositar ?"); //Ask how much the client want deposit
deposit = decimal.Parse(Console.ReadLine());
decimal value = depositarOperacao(debitCard, pin); /*goes to the database for the amount that the customer has in the account*/
decimal saldoAtual = value   deposit; /*calculation of the sum of the balance plus the deposit to give the current balance*/
Console.WriteLine("\n O seu saldo atual é de "   saldoAtual   " euro(s) \n Depósito: "   deposit   " euro(s)");
saldoAtual = updateSaldo(debitCard, pin, saldoAtual);
private static decimal updateSaldo(string numeroCartao, string pin, decimal saldoAtual)
{
    return getDbSaldo($@"UPDATE atmbd.atm Balance='{saldoAtual}' WHERE Pin='{pin}' AND CardNumber = '{numeroCartao}'");
}

private static decimal getDbUpdate(string query)
{
    using (var cn = new SqlConnection("Data Source=MAD-PC-023;Database=atmbd;Trusted_Connection=True;"))
    {
        cn.Open();
        using (var cmd = new SqlCommand() { Connection = cn, CommandText = query })
        {
            var reader = cmd.ExecuteReader();
            if (reader.Read() == true)
            {
                return reader.GetDecimal(0);
            }
            else
            {
                return 0;
            }
        }
    }
}

Now I have to put something save the current balance in the database in case the customer deposits more money add to the current balance.

CodePudding user response:

CommandText=$@"UPDATE atmbd.atm Balance=(Balance {deposit}) WHERE Pin='{pin}' AND CardNumber = '{numeroCartao}'");


var isUpdated=cmd.ExecuteNonQuery();

ExecuteNonQuery used to update,insert and delete.

ExecuteReader used to retrieve more than. ExecuteScalar return one field.

CodePudding user response:

For an update to the database table use the following.

private static bool Update(string cardNumber, string pin, decimal deposit)
{
    using (var cn = new SqlConnection("Data Source=MAD-PC-023;Database=atmbd;Trusted_Connection=True;"))
    {
        using var cmd = new SqlCommand
        {
            Connection = cn,
            CommandText = "UPDATE atmbd.atm SET Balance = Balance   @Deposit WHERE CardNumber = @CardNumber AND Pin = @Pin"
        };
        
        cmd.Parameters.Add("@CardNumber", SqlDbType.NChar).Value = cardNumber;
        cmd.Parameters.Add("@Pin", SqlDbType.NChar).Value = pin;
        cmd.Parameters.Add("@Deposit", SqlDbType.Decimal).Value = deposit;

        cn.Open();
        return cmd.ExecuteNonQuery() == 1;
    }
}
  • Related