背景
操作形式
连接步骤
连接数据库
1 import java.sql.Connection; 2 import java.sql.DriverManager; 3 import java.sql.SQLException; 4 5 public class TestDemo { 6 public static void main(String[] args) { 7 try { 8 Class.forName("com.mysql.jdbc.Driver"); 9 Connection c = DriverManager.getConnection( 10 "jdbc:mysql://127.0.0.1:3306/mysql?serverTimezone=GMT%2B8&characterEncoding=UTF-8&useSSL=false", 11 "root", "Chen1227+"); 12 System.out.println("数据库连接成功!" + c); 13 } catch (ClassNotFoundException e) { 14 e.printStackTrace(); 15 }catch(SQLException e) { 16 e.printStackTrace(); 17 } 18 } 19 }
查询数据
1 import java.sql.Connection; 2 import java.sql.DriverManager; 3 import java.sql.ResultSet; 4 import java.sql.SQLException; 5 import java.sql.Statement; 6 7 public class TestDemo { 8 public static void main(String[] args) { 9 try { 10 // 加载数据库驱动 11 Class.forName("com.mysql.jdbc.Driver"); 12 13 // 连接数据库 14 Connection c = DriverManager.getConnection( 15 "jdbc:mysql://127.0.0.1:3306/mysql?serverTimezone=GMT%2B8&characterEncoding=UTF-8&useSSL=false", 16 "root", "Chen1227+"); 17 System.out.println("数据库连接成功!" + c); 18 19 // 建立连接 20 Statement s = c.createStatement(); 21 System.out.println("获取 Statement对象: " + s); 22 23 // 执行SQL语句 24 String sql = "SELECT order_num, cust_id FROM Orders"; 25 ResultSet re = s.executeQuery(sql); 26 while(re.next()) { 27 int order = re.getInt("order_num"); 28 int cust = re.getInt("cust_id"); 29 System.out.println(order + "," + cust); 30 } 31 System.out.println("执行语句成功!"); 32 33 // 关闭资源 34 re.close(); 35 s.close(); 36 c.close(); 37 System.out.println("资源关闭成功!"); 38 39 } catch (ClassNotFoundException e) { 40 e.printStackTrace(); 41 }catch(SQLException e) { 42 e.printStackTrace(); 43 } 44 } 45 }
原文:https://www.cnblogs.com/cxc1357/p/12470378.html