mysql版本
MySQL Server 8.0
JDBC版本
mysql-connector-java-8.0.25.jar
JDBCDemo
package com.bdqn.jdbc3;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Scanner;
public class JDBCDemo01 {
public static void main(String[] args) throws ClassNotFoundException, SQLException {
Scanner sc = new Scanner(System.in);
System.out.println("请输入用户名:");
String userName = sc.nextLine();
System.out.println("请输入密码:");
String pwd = sc.nextLine();
// 2、获得连接
Connection connection = DBUtils.getConnection();
// 3、获取发送SQL对象
String sql = "select * from user where userName = ? and password=?;";
PreparedStatement preparedStatement = connection.prepareStatement(sql);
// System.out.println(preparedStatement);
// 4、绑定参数,有多少个?绑定多少个参数值
preparedStatement.setString(1, userName);
preparedStatement.setString(2, pwd);
// 5、执行SQL语句,并处理结果
ResultSet resultSet = preparedStatement.executeQuery();
if (resultSet.next()) {
System.out.println("用户名和密码正确,登录成功");
} else {
System.out.println("用户名或密码错误,登录失败");
}
// 6、释放资源:与关闭流的方式一样,先开的后关,后开的先关
DBUtils.closeAll(connection, preparedStatement, resultSet);
sc.close();
}
}
DBUtils
package com.bdqn.jdbc3;
import java.io.IOException;
import java.io.InputStream;
import java.sql.*;
import java.util.Properties;
public class DBUtils {
private static Properties PROPERTIES;
//1.注册驱动
static {
try {
PROPERTIES = new Properties();
InputStream is = DBUtils.class.getClassLoader().getResourceAsStream("db.properties");
PROPERTIES.load(is);
Class.forName(PROPERTIES.getProperty("driver"));
} catch (IOException e) {
throw new RuntimeException(e);
} catch (ClassNotFoundException e) {
throw new RuntimeException(e);
}
}
public static Connection getConnection() {
Connection con = null;
try {
con = DriverManager.getConnection(PROPERTIES.getProperty("url"), PROPERTIES.getProperty("username"), PROPERTIES.getProperty("password"));
} catch (SQLException e) {
throw new RuntimeException(e);
}
return con;
}
public static void closeAll(Connection connection, Statement statement, ResultSet resultSet) {
try {
if (resultSet != null) {
resultSet.close();
}
if (statement != null) {
statement.close();
}
if (connection != null) {
connection.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
db.properties
driver=com.mysql.cj.jdbc.Driver
url=jdbc:mysql://127.0.0.1:3306/java2217?useSSL=false&serverTimezone=UTC
username=root
password=root
8版本之后的properties配置文件的Driver部分,有cj