JDBC连接MYSQL模板
1 package xh.test; 2 3 import java.sql.*; 4 5 public class JdbcConMysql { 6 public static void main(String[] args) { 7 ResultSet rs = null; 8 Statement stmt = null; 9 Connection conn = null; 10 try { 11 Class.forName("com.mysql.jdbc.Driver"); 12 conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/dataBase_name", "username", "password"); 13 stmt = conn.createStatement(); 14 rs = stmt.executeQuery("select * from student"); 15 while (rs.next()) { 16 System.out.print(rs.getInt("id") + " " + rs.getString("name") + " " + rs.getInt("age")); 17 } 18 } catch (SQLException e1) { 19 e1.printStackTrace(); 20 } catch (ClassNotFoundException e) { 21 e.printStackTrace(); 22 } finally { 23 try { 24 if (rs != null) { 25 rs.close(); 26 rs = null; 27 } 28 if (stmt != null) { 29 stmt.close(); 30 stmt = null; 31 } 32 if (conn != null) { 33 conn.close(); 34 conn = null; 35 } 36 } catch (SQLException e) { 37 e.printStackTrace(); 38 } 39 } 40 } 41 }