JDBC操作数据库的基本步骤:
1.注册驱动:
//驱动类com.mysql.jdbc.Driver //就在 mysql-connector-java-5.0.8-bin.jar中 //如果忘记了第一个步骤的导包,就会抛出ClassNotFoundException Class.forName("com.mysql.jdbc.Driver");
2.创建连接:
//2.创建连接 c = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/XXXX?characterEncoding=UTF-8","XXX","XXX");
3.创建statement:
//3.创建statement statement = c.createStatement();
4.执行SQL
statement.execute(sql);
5.关闭连接
//5.关闭连接 if (statement!= null){ try { statement.close(); } catch (SQLException e) { e.printStackTrace(); } }
完整的类如下:
package com.yang.jdbc; import java.sql.*; public class TestJdbc { public static void main(String[] args) { //1.初始驱动 try { //驱动类com.mysql.jdbc.Driver //就在 mysql-connector-java-5.0.8-bin.jar中 //如果忘记了第一个步骤的导包,就会抛出ClassNotFoundException Class.forName("com.mysql.jdbc.Driver"); System.out.println("数据库驱动加载成功!"); Connection c = null; PreparedStatement statement = null; Statement statement1 = null; try { //2.创建连接 c = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/test?characterEncoding=UTF-8","root","admin"); System.out.println("获取连接对象成功"); //在Mysql中,只有当表的类型是INNODB的时候,才支持事务,所以需要把表的类型设置为INNODB,否则无法观察到事务. // //修改表的类型为INNODB的SQL: //alter table hero ENGINE = innodb; //查看表的类型的SQL how2java为数据库名 //show table status from how2java; //开启事务不自动提交 c.setAutoCommit(false); String sql = "select * from userauth"; //3.创建statement //statement1 = c.createStatement(); statement = c.prepareStatement(sql); System.out.println("创建s成功"); //4.执行sql //statement1.execute(sql); statement.executeQuery(); System.out.println("执行查询成功!"); //提交事务 c.commit(); } catch (SQLException e) { e.printStackTrace(); }finally {// //5.关闭连接 if (statement!= null){ try { statement.close(); } catch (SQLException e) { e.printStackTrace(); } } if (c!=null){ try { c.close(); } catch (SQLException e) { e.printStackTrace(); } } } } catch (ClassNotFoundException e) { e.printStackTrace(); }finally { } } }