简体   繁体   中英

Saving int from SQL Server database to c# variable

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 + "'  ";
        }
    }
}

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.

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