用ExecuteScalar()检测用户名和密码是否正确
时间: 2023-12-10 11:38:16 浏览: 85
可以使用 ExecuteScalar() 方法来检测用户名和密码是否正确。假设我们有一个名为 "users" 的表,包含以下列: "id"、 "username" 和 "password"。下面是一个示例代码:
```c#
string connectionString = "Data Source=myServerAddress;Initial Catalog=myDataBase;User ID=myUsername;Password=myPassword;";
string query = "SELECT COUNT(*) FROM users WHERE username=@username AND password=@password";
int result = 0;
using(SqlConnection connection = new SqlConnection(connectionString))
{
SqlCommand command = new SqlCommand(query, connection);
command.Parameters.AddWithValue("@username", "your_username");
command.Parameters.AddWithValue("@password", "your_password");
try
{
connection.Open();
result = (int)command.ExecuteScalar();
}
catch(Exception ex)
{
Console.WriteLine(ex.Message);
}
}
if(result > 0)
{
Console.WriteLine("Login successful");
}
else
{
Console.WriteLine("Invalid username or password");
}
```
这个示例代码会连接到 SQL 数据库,使用参数化查询语句检查用户名和密码是否匹配。如果匹配,那么执行结果将为大于 0 的整数,否则结果为 0。最后根据执行结果输出相应的提示信息。
阅读全文
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![doc](https://img-home.csdnimg.cn/images/20241231044833.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![pptx](https://img-home.csdnimg.cn/images/20241231044947.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)