JDBC的实例
实例1. 使用纯Java的方式连接数据库
3 import java.sql.Connection; 4 import java.sql.DriverManager; 5 import java.sql.SQLException; 6 7 8 public class Test1 { 9 10 public static void main(String[] args){ 11 //1:加载数据库驱动 12 try { 13 Class.forName("com.mysql.jdbc.Driver"); 14 } catch (ClassNotFoundException e) { 15 e.printStackTrace(); 16 } 17 18 19 20 //2:建立连接,获得Connection对象 21 22 //Eclipse:导入包的快捷键:Ctrl+Shift+O 23 //代码的格式化:Ctro+Shift+F 24 25 Connection conn=null; 26 try { 27 conn=DriverManager.getConnection("jdbc:mysql://localhost:3306/day01","root","root"); 28 System.out.println("連接成功"); 29 } catch (SQLException e) { 30 e.printStackTrace(); 31 } 32 //3.获取Statement对象 33 try { 34 stmt=conn.createStatement(); 35 //stmt.execute(sql); 36 stmt.executeUpdate(sql); 37 38 } catch (Exception e) { 39 } 40 41 //4:关闭资源 42 try { 43 conn.close(); 44 } catch (SQLException e) { 45 e.printStackTrace(); 46 } 47 } 48 }
需求:使用ResultSet查询dog信息
1 import java.sql.Connection; 2 import java.sql.DriverManager; 3 import java.sql.ResultSet; 4 import java.sql.Statement; 5 6 /** 7 * 需求:使用ResultSet查询dog信息 8 * 9 * @author10 * 11 */ 12 13 public class Test3 { 14 public static void main(String[] args) { 15 Connection conn = null; 16 Statement stmt = null; 17 ResultSet rs = null; 18 19 String url = "jdbc:mysql://localhost:3306/day01"; 20 String user = "root"; 21 String password = "root"; 22 String sql = "SELECT * FROM dog"; 23 24 try { 25 Class.forName("com.mysql.jdbc.Driver"); 26 conn = DriverManager.getConnection(url, user, password); 27 stmt = conn.createStatement(); 28 rs = stmt.executeQuery(sql); 29 30 // 遍历rs 31 // rs.next();指针下移 32 while (rs.next()) { 33 // 在MySql数据库中index从1开始 34 System.out.println(rs.getObject(1) + "\t"); 35 System.out.println(rs.getObject(2) + "\t"); 36 System.out.println(rs.getObject("health") + "\t"); 37 System.out.println(rs.getObject("love") + "\t"); 38 System.out.println(rs.getObject("strain") + "\t"); 39 40 } 41 42 } catch (Exception e) { 43 44 } finally { 45 try { 46 if (null != rs) { 47 rs.close(); 48 } 49 if (null != stmt) { 50 stmt.close(); 51 } 52 if (null != conn) { 53 conn.close(); 54 } 55 } catch (Exception e2) { 56 } 57 58 } 59 60 } 61 }