Click here to Skip to main content
15,907,329 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
string select = "select COUNT(Bookid) from book1 where Regid='" + TextBox8 + "'";
Posted
Comments
Mathi Mani 19-May-15 13:00pm    
Are you trying to get the count of items with Regid entered by the user in TextBox8? Use TextBox8.Text to get the text instead of passing the TextBox control as input.

Your code is vulnerable to SQL Injection[^].

NEVER use string concatenation to build a SQL query. ALWAYS use a parameterized query.

Once you've fixed that vulnerability, you'll see that you're trying to pass the TextBox control to the query, rather than its .Text property.

C#
using (var connection = new SqlConnection("YOUR CONNECTION STRING"))
using (var command = new SqlCommand("SELECT Count(BookId) FROM book1 WHERE RegId = @RegId"))
{
    command.Parameters.AddWithValue("@RegId", TextBox8.Text);
    
    connection.Open();
    int count = Convert.ToInt32(cmd.ExecuteScalar());
    lblCount.Text = count.ToString();
}
 
Share this answer
 
Comments
PreetamYadav 19-May-15 13:18pm    
ya .text also in this
Sergey Alexandrovich Kryukov 19-May-15 13:57pm    
5ed. And I added some detail on SQL injection in Solution 3.
—SA
Use a SqlCommand object. And since there is only 1 value being returned you can use ExecuteScalar().

C#
...
cmd.CommandText = select;
Int32 count = Int32.Parse(cmd.ExecuteScalar().ToString());
lblCount.Text = count.ToString();
...


Also, as Richard mentions in Solution 2, change your SQL so that you do not have Sql injection issues.
 
Share this answer
 
v2
Your approach is wrong from the very beginning. Your query is composed by concatenation with strings taken from UI. Not only repeated string concatenation is inefficient (because strings are immutable; do I have to explain why it makes repeated concatenation bad?), but there is way more important issue: it opens the doors to a well-known exploit called SQL injection.

This is how it works: http://xkcd.com/327.

The user can add anything in UI elements, including… the fragment of SQL code. Are you getting the idea?

What to do? Just read about this problem and the main remedy: parametrized statements: http://en.wikipedia.org/wiki/SQL_injection.

With ADO.NET, use this: http://msdn.microsoft.com/en-us/library/ff648339.aspx.

Please see my past answers for some more detail:
EROR IN UPATE in com.ExecuteNonQuery();,
hi name is not displaying in name?.

—SA
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900