简体   繁体   中英

C# SQL Server Compact Database Login

I am creating a desktop application in C#. I am creating a Login Form. I have a table named MyTable with columns username and password .

I want to authenticate the user, so I guess I want to know the number of rows affected from SQL query. But every time I got -1 by executing ExecuteNonQuery() method.

My code:

string Username = username.Text;
string Password = password.Text;
SqlCeCommand commandSelect = new SqlCeCommand("SELECT * FROM MyTable WHERE username=@username AND password=@password", connection);
commandSelect.Parameters.AddWithValue("@username", Username);
commandSelect.Parameters.AddWithValue("@password", Password);
int rows = commandSelect.ExecuteNonQuery();
MessageBox.Show(rows.ToString());

Thanks in advance.

You might be better off changing your SQL to get the count like so:

SELECT COUNT(*) FROM MyTable WHERE username=@username AND password=@password

And then use ExecuteScalar() instead of ExecuteNonQuery . This will be less likely to cause you headaches in the future.

I believe ExecuteNonQuery() always returns -1, so don't use that in this case. Steve's answer should do the trick.

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