!注意事项
#编码问题:
设置编译器编码为utf-8
设置数据库编码为uft-8
设置连接编码为utf-8
jdbc的设置:characterEncoding=utf-8
全部的设置:useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTC&verifyServerCertificate=false&useSSL=false

基本操作流程
//以查询为例
引入数据库操作类:
import java.sql.

#1.获取数据库操作对象:
private Connection conn=null;
private PreparedStatement preparedStatement = null;
//private Statement statement=null
private ResultSet resultSet = null;

#2.获取连接(这一部分一般被封装为一个单独的部分)
private static String driverName=”com.mysql.jdbc.Driver”;

private static String url=”jdbc:mysql://localhost:3306/shop”;

private static String user=”root”;
private static String password=””;

try{
Class.forName(driverName);

conn=DriverManager.getConnection(url, user, password);
}catch(SQLException e){
e.printStackTrace();
}catch(ClassNotFoundException e){
e.printStackTrace();
}

#3.执行操作:
String sql=“”;
try{
preparedStatement = conn.prepareStatement(sql);

resultSet=preparedStatement.executeQuery();
//如果是更新操作,则使用executeUpdate()方法
}catch(SQLException e){
e.printStackTrace();
}
#4.获取返回值
if(resultSet.next())//结果默认在第0行,跳传到第一行才能获取数据
String str=resultSet.getString(“name”);
#5.关闭连接:
try {

if (resultSet != null)
resultSet.close();

if (preparedStatement != null)
preparedStatement.close();

if (conn != null)
conn.close();

} catch (SQLException e) {
e.printStackTrace();
}

#增删改查的写法:
预编译sql语句对象preparedStatement一共有两种操作方法
.executeUpdate()
//执行更新、插入、删除
.executeQuery()
//执行查询
预编译sql写法:
String sql=“insert into students values(?,?)”
statement=con.prepareStatement(sql)
statement.setInt(1,80)
statement.setString(2,”jacketzc”)
//set
方法对应sql中的一处‘?’,第一个参数为需要插入的位置,第二个参数为插入的内容
//如果输入内容有特殊字符,预编译语句会做转义处理(避免sql注入),也就是说输入什么,就会执行什么
//条件不能使用占位符!

//非预编译对象不能使用‘?’,只能执行固定的sql语句,操作方法和预编译对象一样
//接受sql语句的方法也不一样
//conn.createStatement.executeQuery(sql)
//非预编译对象容易被sql注入!
//一条被注入的sql语句:where name = ‘’ and passwd=’’ or 1=1

附录:从配置文件加载数据库连接信息
配置文件:jdbc.properties
导入方式:
// 创建一个配置文件对象
Properties properties = new Properties();
// 通过类加载器读取配置
InputStream resourceAsStream = JDBCUtil.class.getClassLoader().getResourceAsStream(“jdbc.properties”);
// 将流对象装载到配置文件中
// System.out.println(resourceAsStream);
properties.load(resourceAsStream);
// System.out.println(properties);
// 从配置文件对象中获取配置信息
String driver = properties.getProperty(“driver”);
String jdbcUrl = properties.getProperty(“jdbcUrl”);
String user = properties.getProperty(“user”);
String password = properties.getProperty(“password”);

获取JDBC连接(单例模式)
JDBC操作mysql - 图1

基本的数据操作(封装与数据库交互的操作,dao层通过继承该类来实现数据库操作)
JDBC操作mysql - 图2

properties标准:
JDBC操作mysql - 图3