//在src下创建dbinfo.properties(/JDBDTest/src/dbinfo.properties)
className=com.mysql.jdbc.Driver url=jdbc:mysql://localhost:3306/mydb2 user=root password=root
package com.huowolf.util; import java.io.InputStream; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.Properties; public class JdbcUtil { private static String className; private static String url; private static String user; private static String password; static{ try { InputStream in = JdbcUtil.class.getClassLoader().getResourceAsStream("dbinfo.properties"); Properties props = new Properties(); props.load(in); className = props.getProperty("className"); url = props.getProperty("url"); user = props.getProperty("user"); password = props.getProperty("password"); Class.forName(className); } catch (Exception e) { e.printStackTrace(); } } public static Connection getConnection() throws Exception{ return DriverManager.getConnection(url, user, password); } public static void release(ResultSet rs,Statement stmt,Connection conn){ try { if(rs!=null) rs.close(); } catch (SQLException e) { e.printStackTrace(); } try { if(stmt!=null) stmt.close(); } catch (SQLException e) { e.printStackTrace(); } try { if(conn!=null) conn.close(); } catch (SQLException e) { e.printStackTrace(); } } }//测试类
package com.huowolf; import java.sql.Connection; import java.sql.ResultSet; import java.sql.Statement; import com.huowolf.util.JdbcUtil; public class JdbcDemo { public static void main(String[] args) { Connection conn = null; Statement stmt = null; ResultSet rs = null; try { conn = JdbcUtil.getConnection(); stmt = conn.createStatement(); rs = stmt .executeQuery("select id,name,password,email,birthday from users"); while (rs.next()) { System.out.println("------------------------"); System.out.println(rs.getObject("id")); System.out.println(rs.getObject("name")); System.out.println(rs.getObject("password")); System.out.println(rs.getObject("email")); System.out.println(rs.getObject("birthday")); } } catch (Exception e) { throw new RuntimeException(e); } finally { JdbcUtil.release(rs, stmt, conn); } } }
原文地址:http://blog.csdn.net/huolang_vip/article/details/46375773