用jdbc写一段根据账号密码登录的语句
时间: 2023-09-27 12:11:58 浏览: 41
下面是使用 JDBC 写一段根据账号密码登录的代码示例:
```
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
public class Login {
public static void main(String[] args) {
Connection connection = null;
PreparedStatement preparedStatement = null;
ResultSet resultSet = null;
try {
// 加载 MySQL JDBC 驱动程序
Class.forName("com.mysql.cj.jdbc.Driver");
// 创建 JDBC 连接
connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/mydatabase", "root", "password");
// 创建 PreparedStatement 对象
String sql = "SELECT * FROM users WHERE username=? AND password=?";
preparedStatement = connection.prepareStatement(sql);
// 设置参数
preparedStatement.setString(1, "username");
preparedStatement.setString(2, "password");
// 执行查询
resultSet = preparedStatement.executeQuery();
// 判断是否登录成功
if (resultSet.next()) {
System.out.println("登录成功");
} else {
System.out.println("登录失败");
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
} finally {
try {
if (resultSet != null) {
resultSet.close();
}
if (preparedStatement != null) {
preparedStatement.close();
}
if (connection != null) {
connection.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
```
在上面的代码中,我们首先创建了一个 `Connection` 对象,然后使用 `DriverManager.getConnection()` 方法创建 JDBC 连接。接着,我们使用 `connection.prepareStatement()` 方法创建 `PreparedStatement` 对象,并设置 SQL 语句和参数。最后,我们执行查询,判断是否登录成功。
注意,上面的代码中的 `username` 和 `password` 应该替换为实际的用户名和密码。