时间:2021-07-01 10:21:17 帮助过:17人阅读
//TestCRUD.java
1 import java.sql.Connection; 2 import java.sql.DriverManager; 3 import java.sql.Statement; 4 5 import org.junit.Before; 6 import org.junit.Test; 7 8 import com.mysql.jdbc.ResultSet; 9 10 /** 11 * 测试增删查改 12 * 13 */ 14 public class TestCRUD { 15 16 private Connection connec; 17 18 /** 19 * 先执行 20 */ 21 @Before 22 public void initConn() { 23 String url = "jdbc:mysql://localhost:3306/mytestbase"; 24 String user = "root"; 25 String password = "root"; 26 // 驱动器管理器 27 try { 28 // 注册驱动程序 29 Class.forName("com.mysql.jdbc.Driver"); 30 connec = DriverManager.getConnection(url, user, password); 31 } catch (Exception e) { 32 e.printStackTrace(); 33 } 34 } 35 /** 36 * insert 37 */ 38 @Test 39 public void insert() { 40 try { 41 // 创建语句对象 42 Statement statement = connec.createStatement(); 43 String sql = "insert into testtable values(‘7‘, ‘opiill‘)"; 44 statement.execute(sql); 45 System.out.println("over"); 46 // 释放资源 47 statement.close(); 48 connec.close(); 49 } catch (Exception e) { 50 e.printStackTrace(); 51 } 52 } 53 54 /** 55 * update 56 */ 57 @Test 58 public void update() { 59 try { 60 // 创建语句对象 61 Statement statement = connec.createStatement(); 62 String sql = "update testtable set psw=‘newpass‘ where id = ‘7‘"; 63 statement.execute(sql); 64 System.out.println("over"); 65 // 释放资源 66 statement.close(); 67 connec.close(); 68 } catch (Exception e) { 69 e.printStackTrace(); 70 } 71 } 72 73 /** 74 * delete 75 */ 76 @Test 77 public void delete() { 78 try { 79 // 创建语句对象 80 Statement statement = connec.createStatement(); 81 String sql = "delete from testtable where id = ‘7‘"; 82 statement.execute(sql); 83 System.out.println("over"); 84 // 释放资源 85 statement.close(); 86 connec.close(); 87 } catch (Exception e) { 88 e.printStackTrace(); 89 } 90 } 91 92 /** 93 * query 94 */ 95 @Test 96 public void query() { 97 try { 98 // 创建语句对象 99 Statement statement = connec.createStatement(); 100 String sql = "select * from testtable"; 101 ResultSet rs = (ResultSet) statement.executeQuery(sql); 102 while (rs.next()) { 103 String id = rs.getString("id"); 104 String psw = rs.getString("psw"); 105 System.out.println(id + ":" + psw); 106 } 107 System.out.println("over"); 108 // 释放资源 109 rs.close(); 110 statement.close(); 111 connec.close(); 112 } catch (Exception e) { 113 e.printStackTrace(); 114 } 115 } 116 }
java18(MySQL)
标签:har 查看 mit exists des upd init 管理器 manager