JavaEE權威讀書筆記(二)JDBC
阿新 • • 發佈:2018-12-11
1,JavaSE
先匯入mysql-connector-java-8.0.12.jar包
插入資料TestInsert.java
import java.sql.*; public class TestInsert { public static void main(String args[]){ try{ Class.forName("com.mysql.jdbc.Driver"); String url = "jdbc:mysql://localhost:3306/training"; String user = "root"; String password = "asdw2012"; Connection cn = DriverManager.getConnection(url, user, password); Statement stmt = cn.createStatement(); stmt.executeUpdate("insert into team (name, slogan, leader) values ('daiwei', 'daiwei', 'daiwei')"); } catch(Exception e){ e.printStackTrace(); } } }
查詢資料TestQuery.java
import java.sql.*; public class TestQuery { public static void main(String args[]){ try{ Class.forName("com.mysql.jdbc.Driver"); String url = "jdbc:mysql://localhost:3306/training"; String user = "root"; String password = "asdw2012"; Connection cn = DriverManager.getConnection(url, user, password); Statement stmt = cn.createStatement(); ResultSet rs = stmt.executeQuery("select * from team"); while(rs.next()){ //System.out.print(rs.getInt("id") + '\t'); System.out.print(rs.getString("name") + '\t'); System.out.print(rs.getString("slogan") + '\t'); System.out.print(rs.getString("leader") + '\t'); } } catch(Exception e){ e.printStackTrace(); } } }