JDBC
JDBC是Java提供的一套类和接口,是一套连接数据库的规范。这套规范面向的是数据库厂商。
JDBC操作数据库的步骤:
1.注册驱动
registerDriver(Driver)
加载驱动类
注意:由于mysql提供的jar包的Driver类中已经注册了一次驱动,使用registerDriver方法注册会导致注册两次驱动,所以注册驱动一般使用反射来注册:
2.获取数据库连接对象
getConnection(url,user,password)
3.通过连接对象来获取sql语句的执行对象。
createStatement();
由于这种方式获取的执行对象无法避免sql注入(SQL注入:在sql语句拼接的时候,可以加入一个恒等条件让这条语句一定会成立
可以通过这个方式,来改变你sql语句原来的意思)所以执行对象一般使用prepareStatement();
4.通过statement对象来执行语句
executeQuery(String sql) 返回值 ResultSet
执行DDL语句。
executeUpdate(String sql) 返回值 int
执行DML,DDL语句
5.处理执行sql语句后得到的结果集
6.关闭资源
调用close方法
对结果集的处理
结果集中有一个指针,每读完一条数据,指针前移一位。
类似集合的遍历,使用while循环
while (result.next()) { // 获取数据方式1 使用字段在表中的位置 int sid = result.getInt(1); System.out.println(sid); // 获取数据方式2 直接使用字段名 String sname = result.getString("sname"); System.out.println(sname); }
PrepareStatement执行sql语句
String sql = "select * from user where userName = ? and passWord = ?"; PreparedStatement statement = connection.prepareStatement(sql); statement.setObject(1, uname); statement.setObject(2, pass);
JDBC工具类的编写
public class JDBC { // 用来接受连接对象 private static Connection connection; private static String url; private static String userName; private static String passWord; private static String driverClass; private JDBC() { } // 注册驱动 static { try { // 从配置文件中读取字符串 readProperties(); Class.forName(driverClass); } catch (IOException e) { System.out.println("配置文件读取失败"); } catch (ClassNotFoundException e) { throw new RuntimeException("驱动注册失败"); } } // 获取连接 public static Connection getConnection() { try { connection = DriverManager.getConnection(url,userName,passWord); } catch (SQLException e) { throw new RuntimeException("数据库连接失败"); } return connection; } // 关闭资源 public static void close(Wrapper ... w) throws SQLException { if (w != null) { for (int i = 0; i < w.length; i++) { if (w[i] instanceof Connection) { ((Connection) w[i]).close(); } else if (w[i] instanceof PreparedStatement) { ((PreparedStatement) w[i]).close(); } else { ((ResultSet) w[i]).close(); } } } } // 读取配置文件 private static void readProperties() throws IOException { Properties properties = new Properties(); // 使用类名获取bin目录下的配置文件的路径 InputStream inputStream = JDBC.class.getClassLoader().getResourceAsStream("db.properties"); properties.load(inputStream); driverClass = properties.getProperty("driverClass"); url = properties.getProperty("url"); userName = properties.getProperty("username"); passWord = properties.getProperty("password"); } }