方式一:创建一个DBHelper类,封装代码,但这种方式导致程序代码的耦合度比较高!
package com.andy.shopping.util.db;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
/**
* 连接数据库类
* @author andy
*
*/
public class DBHelper {
//数据库驱动
private static final String DRIVER = "com.mysql.jdbc.Driver";
//连接数据库的URL地址
private static final String URL = "jdbc:mysql://localhost:3306/数据库名?useUnicode=true&characterEncoding=UTF-8";
//数据库用户名
private static final String USER = "用户名";
//数据库密码
private static final String PASSWORD = "密码";
//创建连接数据库对象
private static Connection connection = null;
/**
* 静态块加载驱动
*/
static {
try {
Class.forName(DRIVER);
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
/**
* 单例模式返回数据库连接对象
* Ctrl+Shif+x:转换字符串大小写快捷键
* @return
*/
public static Connection getConnection(){
if (null == connection) {
try {
connection = DriverManager.getConnect