简体   繁体   中英

Count from SQL Rows into C# textbox

Hi there its the first time to use stackoverflow so hi every one L)

i'm a beginner into C# forms i take it as a fun hobby.

SqlCommand comm = new SqlCommand("SELECT COUNT(*) FROM Members where sponser = "
        +textbox1.text+"'", connection);

 Int32 count = (Int32)comm.ExecuteScalar();
 textbox2.Text ="Found "+ count+" Members;

well its just a mix between 2 codes i have got from google xD how ever the error appear here textbox2.Text ="Found "+ count+" Members;

There are a couple of things wrong with this line of code:

textbox2.Text ="Found "+ count+" Members;

First of all, there's a syntax error. You never close the second set of quotes. You'd do so like this:

textbox2.Text ="Found "+ count+" Members";

However, string concatenation like this is still a little messy. You have two literal strings and you're trying to add them to an integer, which isn't entirely intuitive (and probably slower than it needs to be). Instead, consider using a formatting string:

textbox2.Text = string.Format("Found {0} Members", count);

This will take the value from count (which is an integer) and, internally to the string.Format() function, discern its string representation and insert it into the placeholder in the formatted string.

UPDATE: That takes care of the compile-time errors. Now you're going to get a run-time error from this:

SqlCommand comm = new SqlCommand("SELECT COUNT(*) FROM Members where sponser = "
    +textbox1.text+"'", connection);

As soon as you try to execute that SQL statement you're going to get an error from the database because the resulting query has a syntax error:

SELECT COUNT(*) FROM Members where sponser = some text'

You're missing the opening single-quote for the parameter. Something like this:

SqlCommand comm = new SqlCommand("SELECT COUNT(*) FROM Members where sponser = '"
    +textbox1.text+"'", connection);

However , and this is important , you're still not done. This line of code is wide open to a very common and easily exploitable vulnerability called SQL Injection . You'll want to move away from direct string concatenation and use parameters for your SQL queries. Something like this:

SqlCommand cmd = new SqlCommand("SELECT COUNT(*) FROM Members where sponser = @sponser");
cmd.Parameters.Add("@sponser", textbox1.text);
Int32 count = (Int32)comm.ExecuteScalar();

Know that there is still a lot more you can do to improve this, which is all worth learning over time. Things you can look into are:

  • Checking and validating user input ( textbox1.text ) before you even try to use it in a SQL query.
  • Checking the output of comm.ExecuteScalar() before trying to directly cast it to an Int32 (this would give you a runtime error if it returns anything other than an integer for some reason).
  • Consider using something like Linq to Sql in place of ADO.NET components as it does a lot more for you with less code on your part.

您最后缺少结尾处的“:

textbox2.Text ="Found "+ count+" Members";

You code is vulnerable to SQL Injections . Please consider using Parameters .

private int GetMemberCount(string connectionString, string sponsor)
{
    using(var connection = new SqlConnection(connectionString))
    using(var command = connection.CreateCommand())
    {
        command.CommandText = "SELECT COUNT(*) FROM members WHERE sponsor = @Sponsor";
        command.Parameters.AddWithValue("@Sponsor", sponsor);

        return Convert.ToInt32(command.ExecuteScalar());
    }
}

//Usage
var sponsor = textbox1.text;
var count = GetMemberCount(connectionString, sponsor);

textbox2.Text = string.Format("Found {0} Members", count);
protected void Page_Load(object sender, EventArgs e)
{
    lb1.Text = GetRecordCount(textbox2.Text).ToString();
}

private int GetRecordCount(string myParameter)
{
    string connectionString = ConfigurationManager.ConnectionStrings["DBConnection"].ToString();
    Int32 count = 0;
    string sql = "SELECT COUNT(*) FROM members WHERE sponsor = @Sponsor";
    using (SqlConnection conn = new SqlConnection(connectionString))
    {
        SqlCommand cmd = new SqlCommand(sql, conn);
        cmd.Parameters.Add("@Sponsor", SqlDbType.VarChar);
        cmd.Parameters["@Sponsor"].Value = myParameter;
        try
        {
            conn.Open();
            count = (Int32)cmd.ExecuteScalar();
        }
        catch (Exception ex)
        {

        }
    }
    return (int)count;
}

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