import java.sql.*; public class TestJDBC { /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub Connection con = null; Statement stat = null; ResultSet rs = null; try{ Class.forName("com.mysql.jdbc.Driver"); //con = DriverManager.getConnection("jdbc:mysql://localhost:3306/mydb?user=root&password=root"); con = DriverManager.getConnection("jdbc:mysql://localhost:3306/mydb", "root", "root"); stat = con.createStatement(); rs = stat.executeQuery("select id ,name from people"); while(rs.next()){ System.out.println(rs.getString("id")); } }catch(ClassNotFoundException e){ e.printStackTrace(); }catch(SQLException s){ s.printStackTrace(); }finally{ try{ if(con != null){ //如果con一开始就是null的话,如果不判断就一直出SQL异常,所以应该先判断一下 con.close(); con = null; } if(stat != null){ stat.close(); stat = null; } if(rs != null){ rs.close(); rs =null; } }catch(SQLException se){ se.printStackTrace(); } } } }
java用JDBC连接数据库的写法
最新推荐文章于 2023-07-13 11:33:21 发布