问题原因
![数据库数据正确,查询失败](https://i-blog.csdnimg.cn/blog_migrate/3b6fa80f03dc6bc703b18929dc008cb9.png)
动画演示
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/2c9482cde51cbe1d6573004297acae15.gif)
具体代码
package com.coderitl;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.Scanner;
public class PreJDBCLogin {
public static void main(String[] args) throws Exception {
Class.forName("com.mysql.jdbc.Driver");
Connection connection = DriverManager.getConnection("jdbc:mysql://101.34.1.228:3306/test?autoReconnect=true&useSSL=false", "root", "root");
if (connection != null) {
System.out.println("数据库连接成功");
} else {
System.out.println("数据库连接失败");
}
Scanner scan = new Scanner(System.in);
System.out.println("请输入用户名: ");
String inputUsername = scan.next();
System.out.println("请输入密码: ");
String inputPassword = scan.next();
PreparedStatement preparedStatement = connection.prepareStatement("select username,password from userinfo where username=? and password=?");
preparedStatement.setString(1, inputUsername);
preparedStatement.setString(2, inputPassword);
ResultSet resultSet = preparedStatement.executeQuery();
if (resultSet.next()) {
System.out.println("登录成功");
} else {
System.out.println("登录失败");
}
}
}
解决方案
Connection connection = DriverManager.getConnection("jdbc:mysql://101.34.1.228:3306/test?useUnicode=true&characterEncoding=utf-8&autoReconnect=true&useSSL=false", "root", "root");
- 正确输出
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/e1388516549a84be99e20fd3235372ae.png)