1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37
| public static void main(String[] args) {
Connection con; Statement stm = null; ResultSet rs = null; String driver = "com.mysql.jdbc.Driver"; String url="jdbc:mysql://localhost:3306/cloud_data?useUnicode=true&characterEncoding=UTF-8&zeroDateTimeBehavior=convertToNull&useSSL=true"; String username="root"; String password="123456"; String sql = "select * from dept"; String deptname;
try { Class.forName(driver); con = DriverManager.getConnection(url,username,password); stm = con.createStatement(); rs = stm.executeQuery(sql); while(rs.next()){ deptname = rs.getString("deptname"); System.out.println(deptname); } rs.close(); stm.close(); con.close(); } catch (ClassNotFoundException | SQLException e) { e.printStackTrace(); } }
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32
| public static void main(String[] args) {
Connection con; PreparedStatement pstm; int result; String driver = "com.mysql.jdbc.Driver"; String url="jdbc:mysql://localhost:3306/cloud_data?useUnicode=true&characterEncoding=UTF-8&zeroDateTimeBehavior=convertToNull&useSSL=true"; String username="root"; String password="123456";
try { Class.forName(driver); con = DriverManager.getConnection(url,username,password); pstm = con.prepareStatement("update dept set deptname = ? where deptno = ?"); pstm.setString(1,"物流部门"); pstm.setInt(2,1); result = pstm.executeUpdate(); System.out.println("更新了 "+result+" 条数据"); pstm.close(); con.close(); } catch (ClassNotFoundException | SQLException e) { e.printStackTrace(); } }
|
注:此种方式更加灵活,不管执行多少个此类sql,都只会解析和编译一次,而使用statement则是对每个执行的sql都解析和编译,PreparedStatement 也比 statement 方式更加安全