JDBC 连接 MySQL 数据库

代码如下:

public class JdbcUtils {

public static Connection getConnection() throws Exception {
/**
* 步骤:
* 1. 声明 driver、jdbcUrl、user、password 四个变量
* 2. 新建 jdbc.properties 配置文件,使其在不改源码情况下,变更数据库
* 3. 获取 jdbc.properties 文件参数,利用Java反射和输入流方式获取
* 4. Class.forName(driver);加载驱动
* 5. 获取连接实例
*/
String driver = null;
String jdbcUrl = null;
String user = null;
String password = null;

InputStream inputStream = JdbcUtils.class.getClassLoader().getResourceAsStream("jdbc.properties");
Properties properties = new Properties(http://www.my516.com);
properties.load(inputStream);
driver = properties.getProperty("driver");
jdbcUrl = properties.getProperty("jdbcUrl");
user = properties.getProperty("user");
password = properties.getProperty("password");
Class.forName(driver);
Connection conn = (Connection) DriverManager.getConnection(jdbcUrl, user, password);
return conn;
}

public static void release(Statement statement, Connection conn, ResultSet result) {
try {
if (statement != null) {
statement.close();
}
} catch (Exception e) {
e.printStackTrace();
}
try {
if (conn != null) {
conn.close();
}
} catch (Exception e) {
e.printStackTrace();
}
try {
if (result != null) {
result.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}

}
    这里我写了一个Jdbc获取连接的工具类,只要调用 getConnection() 方法就可以连接成功了。注意一点:MySQL 数据库连接参数为如下(也就是上面代码中注释部分 jdbc.properties 文件内容),否则将连不上,MySQL 端口和用户名都是默认的。
---------------------

原文地址:https://www.cnblogs.com/hyhy904/p/11335078.html