Java中连接MySQL数据库:
第一步:创建jdbc.properties文件
jdbc.driverClassName=com.mysql.jdbc.Driver jdbc.url=jdbc:mysql://localhost:3306/springmybatis jdbc.username=root jdbc.password=5615
第二步:创建DBUtil.java工具类
public class DBUtil { private static String driver = null; private static String url = null; private static String username = null; private static String password = null; static{ Properties pp = new Properties(); try { pp.load(DBUtil.class.getClassLoader().getResourceAsStream("jdbc.properties")); driver = pp.getProperty("jdbc.driverClassName"); url = pp.getProperty("jdbc.url"); username = pp.getProperty("jdbc.username"); password = pp.getProperty("jdbc.password"); Class.forName(driver); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (ClassNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } } public static Connection getConnection(){ Connection conn = null; try { conn = DriverManager.getConnection(url, username, password); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } return conn; } public static void close(Connection conn,PreparedStatement ps,ResultSet rs){ if(conn != null){ if(rs != null){ try { rs.close(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } if(ps != null){ try { ps.close(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } try { conn.close(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } /*public static void main(String[] args) { System.out.println(DBUtil.getConnection()); }*/ }
下面就可以使用数据库了.