数据准备:
- String JDBC_DRIVER = "com.mysql.jdbc.Driver"
- String DB_URL = "jdbc:mysql://localhost:3306/emp";
- String USER = "root";
- String PASS = "123456789";
代码连接:
方法一:
- throws SQLException
- try{ Connection conn = DriverManager.getConnection(DB_URL,USER,PASS);
- Statement stmt = conn.createStatement();
- stmt.close();
- conn.close();
- }catch(SQLException se){
//Handle errors for JDBC
se.printStackTrace();
}catch(Exception e){
//Handle errors for Class.forName
e.printStackTrace();
}finally{
//finally block used to close resources
try{
if(stmt!=null)
stmt.close();
}catch(SQLException se2){
}// nothing we can do
try{
if(conn!=null)
conn.close();
}catch(SQLException se){
se.printStackTrace();
}//end try
取数据:
- String sql;
- ResultSet rs = stmt.executeQuery(sql);
- while(rs.next()){}
- rs.getString("字段名");
- rs.getTimestamp(字段下标);
- rs.close();
方法二:
- PreparedStatement fetch_pst = null;
- Connection conn = new DBUtil().getConn();
- 传递conn
- fetch_pst = conn.prepareStatement(fetch_sql);
- Statement create_pst = conn.createStatement();
- ResultSet fetch_rs = fetch_pst.executeQuery();
- fetch_rs.next()
- fetch_rs.getString(1);
以上是一些经验记录,并不代表所有。