Good afternoon, I'm trying to insert a data into a table that comes from another table like this:
decimal saldo = getDbSaldo($@"SELECT Balance FROM clients WHERE Pin='{pin}' AND CardNumber = '{numeroCartao}'");
insertExtrato($@"insert into MoveInfo (CardNumber, Deposit, Saldo, Withdraw, DataHora) Values({numeroCartao}, {deposit}, {saldo}, {withdraw}, getDate())");
But when I get it working, it always gives me this error:
I've been stuck on this for two days.
CodePudding user response:
Now is the time to replace your SQL-injectable code with parameterized queries.
What's happening is that you're not controlling your SQL code. You're munging strings together and executing them as code. The result could be valid SQL code, could be invalid SQL code, could be malicious, could be anything. You're not in control of it so you don't know.
Always add values as parameters. An example would be:
var query = "insert into MoveInfo (CardNumber, Deposit, Saldo, Withdraw, DataHora) Values(@numeroCartao, @deposit, @saldo, @withdraw, getDate())";
var cmd = new SqlCommand() { Connection = cn, CommandText = query };
cmd.Parameters.Add("@numeroCartao", SqlDbType.Int).Value = numeroCartao;
cmd.Parameters.Add("@deposit", SqlDbType.Decimal).Value = deposit;
cmd.Parameters.Add("@saldo", SqlDbType.Decimal).Value = saldo;
cmd.Parameters.Add("@withdraw", SqlDbType.Decimal).Value = withdraw;
cmd.ExecuteNonQuery();
Note that I completely guessed on the SqlDbType
values to use here. You'll of course want to use whatever matches your database schema.