0

I'm very new to C# but I need to save the results of two columns (balance & withdraw) from a SQL Server database table to C# variables. I have read that you should use SqlDataReader then other things are saying not to and use ExecuteScalar and I'm getting really confused with it all.

Here is the code I have to far. Any help is appreciated thanks.

private void subwithdraw_Click(object sender, EventArgs e)
{
    SqlConnection con = new SqlConnection(@"Data Source=Student04\SQLEXPRESS;Initial Catalog=ATMdata;Integrated Security=True");
    SqlCommand cmd = new SqlCommand("Command String", con);
    SqlDataReader rdr = null;

    try
    {
        using (var check_balance = con.CreateCommand())
        using (var edit_balance = con.CreateCommand())
        using (var edit_withdraw = con.CreateCommand())
        {
            check_balance.CommandText = @"select Balance, Withdraw 
                                          from Cust_details 
                                          Where Account_num ='" + show.AccNo + "'  ";
        }
    }
}
3
  • 1
    Judging from your database name ATMData, security would be an issue (also if you're a student). Your query is vulnarable to SQL Injection, you should use parameterized queries. Commented Dec 17, 2015 at 13:20
  • What are the type of your Balance and Withdraw columns? Commented Dec 17, 2015 at 13:26
  • thanks ill have a read on parameterized queries and both of the columns are integers Commented Dec 17, 2015 at 13:35

1 Answer 1

2

I assume your query return one row, you can generate them with using ExecuteReader method as;

using(var rdr = check_balance.ExecuteReader())
{
   while(rdr.Read())
   {
       int balance = rdr.GetInt32(0);
       int withdraw= rdr.GetInt32(1);
   }
}

ExecuteScalar wouldn't fit for your case since it returns first column of the first row of your query. Other columns are ignored.

But more important, you should always use parameterized queries. This kind of string concatenations are open for SQL Injection attacks.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.