JDBCUtils

xiaoxiao2021-02-28  24

V1 版本一:

import java.sql.Connection;import java.sql.DriverManager;import java.sql.PreparedStatement;import java.sql.ResultSet;import java.sql.SQLException;

public class JDBCUtils_V1 { /** * 获取连接方法 * @return */ public static Connection getConnection() { Connection conn = null; try { Class.forName("com.mysql.jdbc.Driver"); conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/jdbctest", "root", "950811"); } catch (Exception e) { e.printStackTrace(); } return conn; } public static void release(Connection conn, PreparedStatement pstmt, ResultSet rs) { if (rs != null) { try { rs.close(); } catch (SQLException e) { e.printStackTrace(); } } if (pstmt != null) { try { pstmt.close(); } catch (SQLException e) { e.printStackTrace(); } } if (conn != null) { try { conn.close(); } catch (SQLException e) { e.printStackTrace(); } } }

}

V2 版本二

db.properties 代码:

driver=com.mysql.jdbc.Driverurl=jdbc:mysql://localhost:3306/jdbctest?useUnicode=true&characterEncoding=utf8username=root

password=950811

V2 代码:

import java.sql.Connection;import java.sql.DriverManager;import java.sql.PreparedStatement;import java.sql.ResultSet;import java.sql.SQLException;import java.util.ResourceBundle;

public class JDBCUtils_V2 { private static String driver; private static String url; private static String username; private static String password; /** * 静态代码块加载配置文件信息 */ static{ ResourceBundle bundle = ResourceBundle.getBundle("db"); driver = bundle.getString("driver"); url = bundle.getString("url"); username = bundle.getString("username"); password = bundle.getString("password"); } /** * 获取连接方法 * @return */ public static Connection getConnection() { Connection conn = null; try { Class.forName(driver); conn = DriverManager.getConnection(url, username, password); } catch (Exception e) { e.printStackTrace(); } return conn; } public static void release(Connection conn, PreparedStatement pstmt, ResultSet rs) { if (rs != null) { try { rs.close(); } catch (SQLException e) { e.printStackTrace(); } } if (pstmt != null) { try { pstmt.close(); } catch (SQLException e) { e.printStackTrace(); } } if (conn != null) { try { conn.close(); } catch (SQLException e) { e.printStackTrace(); } } }

}

---------------------------------------------------------------------------------------------------------------------

转载请注明原文地址: https://www.6miu.com/read-2450370.html

最新回复(0)