-3

I have the following code to check a user:

    private void button1_Click(object sender, EventArgs e)
    {

        string ss = "SElECT * FROM 123 WHERE u=@USERNAME";
        using (SqlCeConnection cn = new SqlCeConnection(@"Data Source=|DataDirectory|\123.sdf"))       
        {
            try
            {
                SqlCeCommand selectCommand = new SqlCeCommand(ss, cn);
                cn.Open();

                selectCommand.Parameters.AddWithValue("@USERNAME", textBox1.Text);

                int result = (int) selectCommand.ExecuteScalar();
                if (result > 0)
                    MessageBox.Show("logged in");
                else
                    MessageBox.Show("user not found");
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
            finally
            {
                cn.Close();
            }
        }              
    }

I get this error when I run it:

Error

Why am I getting this error?

J0e3gan
  • 8,740
  • 10
  • 53
  • 80
kipo
  • 63
  • 1
  • 1
  • 6

3 Answers3

1
string ss = "SElECT * FROM [123] WHERE u=@USERNAME";
  • @kipo ask one by one question. Venkat answer your question for another problems add new question. – mybirthname Oct 25 '14 at 06:43
  • @kipo Well what do you expect if you execute a query that doesn't return an `int`, and try to cast it to an `int`? Pay attention to what your system is telling you. Fix it by casting to whatever type the query does return. –  Oct 25 '14 at 06:43
  • @kipo `int result = (int) selectCommand.ExecuteScalar();` which will return single value but you executed `select * from [123]` change it to count(*) as Damith said – Venkataraghavan Yanamandram Oct 25 '14 at 06:58
1

change your SQL statement as below

string ss = "SElECT Count(*) FROM [123] WHERE u=@USERNAME";

ExecuteScalar will give you the value of first row, first column. if that is not an integer value you will get exception when casting to int. include Count(*) in your sql and it will give you the number of records which match your condition and also casting will work. Note that I have added [] for table name too.

Damith
  • 62,401
  • 13
  • 102
  • 153
  • IF i want to do same but with another query like this : https://www.dropbox.com/s/d67yetknugj663i/qup.PNG?dl=0 – kipo Oct 25 '14 at 08:48
0

FROM 123 is incorrect. You need the name of a table here.

trnelson
  • 2,715
  • 2
  • 24
  • 40