Java连接MySQL

xiaoxiao2021-02-28  6

首先要导入mysql驱动,然后创建一个工具类JDBCUtil

public class JDBCUtil { private static final String driverName = "com.mysql.jdbc.Driver"; private static final String CONNURL = "jdbc:mysql://localhost:3306/<表名>?useUnicode=true&characterEncoding=utf8"; private static final String USERNAME = "your db username"; private static final String PASSWORD = "your db password"; /*使用静态代码块完成驱动的加载*/ static { try { Class.forName(driverName); } catch (ClassNotFoundException e) { e.printStackTrace(); } } /*提供连接的方法*/ public static Connection getConnection() { Connection con = null; try { //连接指定的MMySQL数据库,三个参数分别是:数据库地址、账号、密码 con = DriverManager.getConnection(CONNURL, USERNAME, PASSWORD); } catch (Exception e) { e.printStackTrace(); } return con; } /*关闭连接的方法*/ public static void close(ResultSet rs, Statement stmt, Connection con) { try { if (rs != null) rs.close(); } catch (Exception ex) { ex.printStackTrace(); } try { if (stmt != null) stmt.close(); } catch (Exception ex) { ex.printStackTrace(); } try { if (con != null) con.close(); } catch (Exception ex) { ex.printStackTrace(); } } }
转载请注明原文地址: https://www.6miu.com/read-1750015.html

最新回复(0)