user3103779
user3103779

Reputation: 7

adding the value of a column of database in c#

I want to add the value of a database column in c# and want to save it in a variable . Please help me to ahead. Thanks in advance.

I thought the following: it is possible,

SqlCommand myCommand3 = new SqlCommand("select sum(credit_hour) from [student_reg] WHERE [std_id]= '" + id + "' ", myConnection);

Upvotes: 0

Views: 50

Answers (2)

Sudhakar Tillapudi
Sudhakar Tillapudi

Reputation: 26219

Yes it is possible.

Problem 1: You don't need to enclose the Integer parameters within single quotes.

Solution 1:

SqlCommand myCommand3 = new SqlCommand("select sum(credit_hour) from 
                [student_reg] WHERE [std_id]= " + id, myConnection);

Suggestion: Your Query is open to SQL Injection Attacks i would suggest you to use Parameterised Queries to avoid them.

Solution 2: Using Parameterised Queries

SqlCommand myCommand3 = new SqlCommand("select sum(credit_hour) from 
                [student_reg] WHERE [std_id]= @id", myConnection);
myConnection.Open();
myCommand3.Parameters.AddWithVlaue("@id",id);
TextBox1.Text  = myCommand3.ExecuteScalar().ToString();

Upvotes: 1

Arjit
Arjit

Reputation: 3456

Try this.

    SqlCommand myCommand3 = new SqlCommand("select sum(credit_hour) from [student_reg] WHERE [std_id]= @Id ", myConnection);
    myCommand3.Parameters.AddWithValue("@Id", id);
    con.Open();
    int sum = (int) myCommand3.ExecuteScalar();

Upvotes: 0

Related Questions