本文共 926 字,大约阅读时间需要 3 分钟。
学习记录:复习
JDBC简单链接数据库
/** 关闭资源用 */ Connection conn = null; Statement stmt = null; ResultSet rest = null; /** 设置url,user,password,sql */ String url = "jdbc:mysql://localhost:3306/kevin?useUnicode=true&characterEncoding=utf-8"; String user = "root"; String password = "123456"; String sql = "select * from blog"; try { // 注册驱动 Class.forName("com.mysql.jdbc.Driver"); // 获得数据库链接 conn = DriverManager.getConnection(url, user, password); // 获得Statement stmt = conn.createStatement(); rest = stmt.executeQuery(sql); while (rest.next()) { System.out.println(rest.getString("title") + "_" + rest.getString("viceTitle")); } } catch (Exception e) { System.err.println("发生异常:"+e); } finally {//关闭资源 rest.close(); stmt.close(); conn.close(); }
关闭资源放在finally中
需引入mysql-connector-java-***.jar,如果没有使用maven可在或