Question

I'm getting a run time error in my program when connecting to a SQL Server CE database.

Can anyone help me, and please don't write the whole code just a line of what needs to be changed to.

Here is my code:

string conString = Properties.Settings.Default.POSdatabaseConnectionString;

using (SqlCeConnection con = new SqlCeConnection(conString))
{
    con.Open();
    using (SqlCeCommand com = new SqlCeCommand("SELECT * FROM Customer where Customer ID ='" + this.useridtexbox.Text + "' and Name='" + this.nametexbox.Text + "'", con))
    {
        SqlCeDataReader reader = com.ExecuteReader();
        int count = 0;

        while (reader.Read())
        {
            count = count + 1;
        }

        if (count == 1)
        {
           MessageBox.Show("You have logged in succesfully");
           Homepage homepage = new Homepage();
           homepage.Show();
           homepage.LabelText = ("Welcome " + reader["name"].ToString());
        }
        else
        {
           MessageBox.Show("Username and password is Not correct ...Please try again");
           con.Close();
        } 

Error:

There was an error parsing the query. [ Token line number = 1,Token line offset = 39,Token in error = ID ]

Was it helpful?

Solution 2

In your command, do not use string concatenation. That will fail badly and leave you open to SQL injection attacks.

Image what happens if I enter the following text into this.nametexbox.Text:

Joe'; DROP DATABASE; --

You don't want have someone like little Bobby Tables as user.

Use sql parameters.

If you have tables or fields with spaces, you to have a word with your DBA. If you cannot change it, make sure you use the correct syntax:

WHERE [Customer ID] = '12345'

OTHER TIPS

I think the problem with the space in Customer ID,Try this

SqlCeCommand com = new SqlCeCommand("SELECT * FROM Customer where CustomerID ='" +    this.useridtexbox.Text + "' and Name='" + this.nametexbox.Text + "'", con))

Make sure you CustomerID column have space

Always use parameterized query to avoid SQL Injection

How does SQLParameter prevent SQL Injection

SqlCeCommand com = new SqlCeCommand = "SELECT * FROM Customer where CustomerID=@CustomerID and  
                                name=@name";
con.Parameters.AddWithValue("@CustomerID", valuesTextBox.Text);
con.Parameters.AddWithValue("@name", namwTextBox.Text);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top