首先要导入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();
}
}
}