Java中JDBC的使用
1、注册驱动
1 Driver driver = new com.nysql.jdbc.Driver(); 2 DriverMabeger.registerDriver(driver);
2、获取数据库链接
1 String url = "jdbc:mysql://127.0.0.1:3306/bd171"; 2 String user = "root"; 3 String passwd = "root"; 4 Connection connection = DriverManager.getConnection(url,user,passwd);
3、获取数据库操作对象
1 Statement statement = connection.createStatement();
4、执行sql语句
1 String sql = ""; 2 ResultSet resultSet = statement.excuteQuery(sql);
5、处理查询结果
1 while(resultSet.next()) 2 { 3 int id = resultSet.getInt("id"); 4 String last_name = resultSet.getString("last_name"); 5 souble salary = resultSet.getDouble("salary"); 6 }
6、关闭连接
//关闭链接是从最底层开始关闭 if(resultSet != null) { resultSet.close(); } if(statement!= null) { statement.close(); } if(connection!= null) { connection.close(); }
实现代码
1 import java.sql.*; 2 3 /* 4 * 第六步:关闭资源 5 * */ 6 public class JDBCTest06 { 7 public static void main(String[] args) { 8 Driver driver = null; 9 Connection connection = null; 10 Statement statement = null; 11 ResultSet resultSet = null; 12 try { 13 //1 注册驱动 14 driver = new com.mysql.jdbc.Driver(); 15 DriverManager.registerDriver(driver); 16 17 //2 获取数据库链接 18 String url = "jdbc:mysql://127.0.0.1:3306/bd171"; 19 String user = "root"; 20 String passwd = "root"; 21 connection = DriverManager.getConnection(url, user, passwd); 22 23 //3 获取数据库操作对象 24 statement = connection.createStatement(); 25 26 //4 执行sql语句 27 String sql = "select id,last_name,salary from s_emp"; 28 resultSet = statement.executeQuery(sql); 29 30 //5 处理查询结果 31 while (resultSet.next()){ 32 int id = resultSet.getInt("id"); 33 String last_name = resultSet.getString("last_name"); 34 double salary = resultSet.getDouble("salary"); 35 System.out.println(id+" "+last_name+" "+salary); 36 } 37 }catch (Exception e){ 38 e.printStackTrace(); 39 }finally { 40 //6 关闭资源 --> 从最底层开始关闭 41 if (resultSet != null) 42 { 43 try { 44 resultSet.close(); 45 } catch (SQLException throwables) { 46 throwables.printStackTrace(); 47 } 48 } 49 50 if (statement != null) 51 { 52 try { 53 statement.close(); 54 } catch (SQLException throwables) { 55 throwables.printStackTrace(); 56 } 57 } 58 59 if (connection != null) 60 { 61 try { 62 connection.close(); 63 } catch (SQLException throwables) { 64 throwables.printStackTrace(); 65 } 66 } 67 68 } 69 } 70 }

浙公网安备 33010602011771号