一、引jar包:mysql-connector-java
二、代码
public class JdbcApplication { public static void main(String[] args) { /* 1、DriverManager 1、注册驱动:void registerDriver(java.sql.Driver) * Class.forName("com.mysql.cj.jdbc.Driver"):jvm加载com.mysql.cj.jdbc.Driver类, 执行静态代码块,静态代码块中会调用DriverManager的registerDriver方法,从而注册驱动。 * Class.forName("com.mysql.cj.jdbc.Driver")可以省略:DriverManager会读取META-INF /services/java.sql.Driver文件,从而获取驱动类。 2、获取数据库连接:Connection getConnection(String,String,String) 2、Connection 1、获取执行sql的对象 * Statement createStatement():存在sql注入问题 * PreparedStatement prepareStatement(String):解决sql注入问题 参数:为sql语句字符串,[?]为占位符 2、管理事务 * void setAutoCommit(boolean):参数:true表示关闭事务,false表示开启事务 * void commit():提交事务 * void rollback():事务回滚 3、Statement 1、执行sql * boolean execute(String):执行任意sql语句 * int executeUpdate(String):执行增删改语句;返回值:数据行变化条数 * ResultSet executeQuery(String):执行查语句 4、ResultSet 1、boolean next():游标向下移动一行 2、xxx getXxx(int/String): xxx:字段的数据类型(String、int...) 参数:int:字段的索引(从1开始);String:字段的名称 5、PreparedStatement 1、void setXxx(int,xxx): xxx:占位符?的数据类型(String、int...) 参数1:占位符?的索引(从1开始) 参数2:占位符?的值 2、执行sql ResultSet executeQuery():查操作 int executeUpdate():增删改操作 获取src路径下的文件的方式: ClassLoader classLoader = JdbcApplication.class.getClassLoader(); URL url = classLoader.getResource("jdbc.properties"); String path = url.getPath(); */ Connection connection = null; PreparedStatement preparedStatement = null; ResultSet resultSet = null; try { //连接数据库 Class.forName("com.mysql.cj.jdbc.Driver"); connection = DriverManager.getConnection( "jdbc:mysql://172.21.22.5:3306/studymysql", "root", "123456"); //开启事务 connection.setAutoCommit(false); //定义sql,创建statement,执行sql String sql = "select * from student where age > ?"; preparedStatement = connection.prepareStatement(sql); preparedStatement.setInt(1, 20); resultSet = preparedStatement.executeQuery(); //事务提交 connection.commit(); //处理 while (resultSet.next()) { int id = resultSet.getInt(1); String name = resultSet.getString(2); int age = resultSet.getInt(3); System.out.println("{id:" + id + ",name:" + name + ",age:" + age + "}"); } } catch (Exception throwables) { //事务回滚 if (connection != null) { try { connection.rollback(); } catch (SQLException e) { e.printStackTrace(); } } throwables.printStackTrace(); } finally { //关闭资源 if (resultSet != null) { try { resultSet.close(); } catch (SQLException throwables) { throwables.printStackTrace(); } } if (preparedStatement != null) { try { preparedStatement.close(); } catch (SQLException throwables) { throwables.printStackTrace(); } } if (connection != null) { try { connection.close(); } catch (SQLException throwables) { throwables.printStackTrace(); } } } } }
三、指定字符编码
jdbc:mysql://192.168.2.120:3306/sp?characterEncoding=utf8&useSSL=false