package jdbc.jdbc; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.Statement; /** * 第一个JDBC * @author noteless */ public class FirstJDBC { public static void main(String[] args) throws Exception { //一、注册驱动 Class.forName("com.mysql.jdbc.Driver"); //数据库链接所需参数 String user = "root"; String password = "123456"; String url = "jdbc:mysql://localhost:3306/sampledb?useUnicode=true&characterEncoding=utf-8"; //二、获取链接对象 Connection conn = DriverManager.getConnection(url, user, password); //设置sql语句 String sql = "select * from student"; //三、得到sql语句执行对象 Statement stmt = conn.createStatement(); //四、执行sql并保存结果集 ResultSet rs = stmt.executeQuery(sql); //五、处理结果集 while (rs.next()) { System.out.print("id:" + rs.getInt(1)); System.out.print(",姓名:" + rs.getString(2)); System.out.print(",年龄:" + rs.getInt(3)); System.out.println(",性别:" + rs.getString(4)); } //六、资源关闭 rs.close(); stmt.close(); conn.close(); } }
package jdbc; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; public class FirstJDBCFormal { public static void main(String[] args) throws Exception { //一、注册驱动 Class.forName("com.mysql.jdbc.Driver"); //数据库链接所需参数 String user = "root"; String password = "123456"; String url = "jdbc:mysql://localhost:3306/sampledb?useUnicode=true&characterEncoding=utf-8"; Connection conn = null; Statement stmt = null; ResultSet rs = null; try { //二、获取链接对象 conn = DriverManager.getConnection(url, user, password); //三、设置sql语句 String sql = "select * from student"; //四、得到sql语句执行对象 stmt = conn.createStatement(); //五、执行并保存结果集 rs = stmt.executeQuery(sql); //六、处理结果集 while (rs.next()) { System.out.print("id:" + rs.getInt(1)); System.out.print(",姓名:" + rs.getString(2)); System.out.print(",年龄:" + rs.getInt(3)); System.out.println(",性别:" + rs.getString(4)); } } catch (Exception e) { throw new RuntimeException(e); } finally { //七、资源关闭 try { if (conn != null) { conn.close(); } if (rs != null) { rs.close(); } if (stmt != null) { stmt.close(); } } catch (SQLException e) { } } } }
if (conn != null) { try{ conn.close(); }catch (SQLException e){ } } if (rs != null) { try{ rs.close(); }catch (SQLException e){ } } if (stmt != null) { try{ stmt.close(); }catch (SQLException e){ } }
try{ //... }catch(SQLException ex) { while(ex != null) { System.out.println("SQLState:" + ex.getSQLState()); System.out.println("Error Code:" + ex.getErrorCode()); System.out.println("Message:" + ex.getMessage()); Throwable t = ex.getCause(); while(t != null) { System.out.println("Cause:" + t); t = t.getCause(); } ex = ex.getNextException(); } }
try{ //... }catch(SQLException ex) { for(Throwable e : ex ) { System.out.println("Error encountered: " + e); } }