java实现登录的样例
时间: 2023-08-24 14:04:47 浏览: 45
以下是一个简单的Java登录样例,使用JDBC连接数据库验证用户输入的用户名和密码是否正确。
```java
import java.sql.*;
public class LoginExample {
public static void main(String[] args) {
String url = "jdbc:mysql://localhost:3306/mydatabase";
String username = "root";
String password = "password";
String query = "SELECT * FROM users WHERE username=? AND password=?";
try {
// 创建数据库连接
Connection conn = DriverManager.getConnection(url, username, password);
// 创建PreparedStatement对象
PreparedStatement stmt = conn.prepareStatement(query);
// 获取用户输入的用户名和密码
String inputUsername = "testuser";
String inputPassword = "testpassword";
// 设置参数值
stmt.setString(1, inputUsername);
stmt.setString(2, inputPassword);
// 执行查询
ResultSet rs = stmt.executeQuery();
// 判断是否有匹配的记录
if (rs.next()) {
System.out.println("登录成功!");
} else {
System.out.println("用户名或密码错误!");
}
// 关闭资源
rs.close();
stmt.close();
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
```
在此示例中,我们使用MySQL数据库来存储用户信息。首先,我们需要建立与数据库的连接,并创建一个PreparedStatement对象,然后将用户输入的用户名和密码与查询语句中的占位符进行匹配,执行查询并判断是否有匹配的记录。最后,我们关闭资源并处理任何可能的异常。
相关推荐
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)