1 public class MySqlDemo { 2 private static final String DRIVER_CLASS = "com.mysql.cj.jdbc.Driver"; 3 private static final String URL = "jdbc:mysql://localhost:3306/test?serverTimezone=UTC"; 4 private static final String USER = "root"; 5 private static final String PASSWORD = "123456"; 6 7 public static void main(String[] args) { 8 try { 9 //1.加载驱动 10 Class.forName(DRIVER_CLASS); 11 //2.通过驱动连接数据库 12 Connection conn = DriverManager.getConnection(URL,USER,PASSWORD); 13 //3.执行数据的增删查改功能 14 //查 15 Statement st = conn.createStatement(); 16 ResultSet rs = st.executeQuery("select * from websites"); 17 //4.获得数据库的返回结果 18 while (rs.next()) { 19 System.out.println(rs.getString("id")+"---"+rs.getString("name")+"---" 20 +rs.getString("url")+"---"+rs.getString("alexa")+rs.getString("country")); 21 } 22 23 /* 24 //增 25 //设置手动提交事务 26 conn.setAutoCommit(false); 27 PreparedStatement ps = conn.prepareStatement("insert into websites(name,url,alexa,country)values('lzy','www.baidu.com',12,'uss')"); 28 ps.executeUpdate(); 29 //提交事务 30 conn.commit();*/ 31 32 /* 33 //改 34 conn.setAutoCommit(false); 35 PreparedStatement ps = conn.prepareStatement("update websites set name='xxx'where id=11"); 36 ps.executeUpdate(); 37 conn.commit();*/ 38 39 /* 40 //删 41 conn.setAutoCommit(false); 42 PreparedStatement ps = conn.prepareStatement("delete from websites where name='xxx'"); 43 ps.executeUpdate(); 44 conn.commit(); 45 conn.close();*/ 46 } catch (ClassNotFoundException e) { 47 // TODO Auto-generated catch block 48 e.printStackTrace(); 49 } catch (SQLException e) { 50 // TODO Auto-generated catch block 51 e.printStackTrace(); 52 } 53 } 54 55 56 }
1 package com.util; 2 3 import java.sql.*; 4 5 public class DBconn { 6 static String url = "jdbc:mysql://localhost:3306/test?useunicuee=true& characterEncoding=utf8"; 7 static String username = "root"; 8 static String password = "root"; 9 static Connection conn = null; 10 static ResultSet rs = null; 11 static PreparedStatement ps =null; 12 public static void init(){ 13 try { 14 Class.forName("com.mysql.jdbc.Driver"); 15 conn = DriverManager.getConnection(url,username,password); 16 } catch (Exception e) { 17 System.out.println("init [SQL驱动程序初始化失败!]"); 18 e.printStackTrace(); 19 } 20 } 21 public static int addUpdDel(String sql){ 22 int i = 0; 23 try { 24 PreparedStatement ps = conn.prepareStatement(sql); 25 i = ps.executeUpdate(); 26 } catch (SQLException e) { 27 System.out.println("sql数据库增删改异常"); 28 e.printStackTrace(); 29 } 30 31 return i; 32 } 33 public static ResultSet selectSql(String sql){ 34 try { 35 ps = conn.prepareStatement(sql); 36 rs = ps.executeQuery(sql); 37 } catch (SQLException e) { 38 System.out.println("sql数据库查询异常"); 39 e.printStackTrace(); 40 } 41 return rs; 42 } 43 public static void closeConn(){ 44 try { 45 conn.close(); 46 } catch (SQLException e) { 47 System.out.println("sql数据库关闭异常"); 48 e.printStackTrace(); 49 } 50 } 51 }