用IDEA编写一个较为常用的JDBC程序,配置相关环境及解决出现的问题。
程序如下:
方式1、直接在类中配置数据库相关属性
import java.sql.*;
/**
* 工具类
*/
final class JdbcUtils {
// test是我自己的一个数据库,如果在本机操作的话,localhost:3306可以省略,即直接///的形式
private static String url = "jdbc:mysql://localhost:3306/test";
private static String user = "root";
private static String password = "******";
private JdbcUtils() {
}
// 注册驱动
static {
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException e) {
throw new ExceptionInInitializerError(e);
}
}
/**
* 建立连接
*
* @return
* @throws SQLException
*/
public static Connection getConnect() throws SQLException {
return DriverManager.getConnection(url, user, password);
}
/**
* 释放资源
*
* @param rs
* @param st
* @param conn
*/
public static void free(ResultSet rs, Statement st, Connection conn) {
try {
if (rs != null) {
rs.close();
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
try {
if (st != null) {
st.close();
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
if