//此連接是針對于MySQL的連接
public class MybatisJdbcConnection {
public static void main(String[] args){ Connection conn = null; ResultSet res = null; PReparedStatement prepareStatement=null; try { //加載數據庫驅動 Class.forName("com.mysql.jdbc.Driver"); //獲得數據庫連接池 conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/mybatis?characterEncoding=utf-8", "root", "root"); //定義sql語句 String sql = "select * from user where username = ?"; //得到預處理statement prepareStatement = conn.prepareStatement(sql); //設置參數,?代表的是需要查詢的條件也就是參數從1開始,有幾個就設置幾個 prepareStatement.setString(1, "王五"); //向數據庫發出sql執行查詢 ,查詢出結果集 res = prepareStatement.executeQuery(); //遍歷結果集 while(res.next()){ String userid = res.getString("id"); String username = res.getString("username"); System.out.println("..."+userid+"...."+username+"...."); } } catch (Exception e) { e.printStackTrace(); }finally{ //釋放資源 if(res!=null){ try { res.close(); } catch (SQLException e) { e.printStackTrace(); } } if(prepareStatement!=null){ try { prepareStatement.close(); } catch (SQLException e) { e.printStackTrace(); } } if(conn!=null){ try { conn.close(); } catch (SQLException e) { e.printStackTrace(); } } } }}
新聞熱點
疑難解答