Java DataBase Connection

来源:互联网 发布:中易智联软件多少钱 编辑:程序博客网 时间:2024/04/30 15:34

// DB.java

import java.sql.Connection;import java.sql.DriverManager;import java.sql.PreparedStatement;import java.sql.ResultSet;import java.sql.SQLException;import java.sql.Statement;//封装DB,增强程序维护的维护性public class DB {private final static String DRIVER_CLASS="com.mysql.jdbc.Driver";//驱动类路径private final static String URL="jdbc:mysql://127.0.0.1:3306/test";//连接字符串private final static String USER="root";//数据库用户名private final static String PASSWORD="root";//数据库密码//获得连接Connectionpublic static Connection getConnection() {Connection conn = null;try {Class.forName(DRIVER_CLASS);//建立连接conn = DriverManager.getConnection(URL,USER,PASSWORD);} catch (ClassNotFoundException e) {e.printStackTrace();} catch (SQLException e) {e.printStackTrace();}return conn;}//获得语句对象Statementpublic static Statement getStatement(Connection conn) {Statement stmt = null; try {if(conn != null) {stmt = conn.createStatement();}} catch (SQLException e) {e.printStackTrace();}return stmt;}//获得语句对象PreparedStatementpublic static PreparedStatement getPreparedStatement(Connection conn,String sql) {PreparedStatement ps = null; try {if(conn != null) {ps = conn.prepareStatement(sql);}} catch (SQLException e) {e.printStackTrace();}return ps;}//获得结果集ResultSetpublic static ResultSet getResultSet(Statement stmt, String sql) {ResultSet rs = null;try {if(stmt != null) {rs = stmt.executeQuery(sql);}} catch (SQLException e) {e.printStackTrace();}return rs;}//获得结果集ResultSetpublic static int getResultInt(Statement stmt, String sql) {int cnt = 0;try {if(stmt != null) {cnt = stmt.executeUpdate(sql);}} catch (SQLException e) {e.printStackTrace();}return cnt;}//关闭连接public static void closeConnection(Connection conn) {try {if(conn != null) {conn.close();conn = null;}} catch (SQLException e) {e.printStackTrace();}}//关闭语句对象Statementpublic static void closeStatement(Statement stmt) {try {if(stmt != null) {stmt.close();stmt = null;}} catch (SQLException e) {e.printStackTrace();}}//关闭结果集ResultSetpublic static void closeResultSet(ResultSet rs) {try {if(rs != null) {rs.close();rs = null;}} catch (SQLException e) {e.printStackTrace();} }}


 


//Test.java

class Test{public static void main(String args []){DB.getConnection(); }}