创建一个子类,用于封装DB操作
public class MyDBUtils {
public static Connection getMyDataBaseConnection(){
String driver = "com.mysql.jdbc.Driver";
String url = "jdbc:mysql://localhost:3306/db_ebuy";
String username = "root";
String password = "密码";
//加载驱动
try {
Class.forName(driver);
System.out.println("驱动加载成功");
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
System.out.println("驱动加载失败");
e.printStackTrace();
}
//连接数据库
Connection conn = null;
try {
conn = DriverManager.getConnection(url, username, password);
if(!conn.isClosed()){
System.out.println("数据库连接成功");
}
} catch (SQLException e) {
// TODO Auto-generated catch block
System.out.println("数据库连接失败");
e.printStackTrace();
}
return conn;
}
}
在业务逻辑中:
Connection conn = DBUtils.getDataBaseConnection();
try {
Statement statement = (Statement) conn.createStatement();
ResultSet rs = statement.executeQuery("select * from t_user");
List<User> userList = new ArrayList<User>();
userList = DBUtils.convertList(rs);
for(int i = 0;i<userList.size();i++){
System.out.println(userList.get(i));
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
PreparedStatement pStatement = (PreparedStatement) conn.prepareStatement("update t_tag set name='音乐' where name='测试'");
if(pStatement.executeUpdate() != 0){
System.out.println("更新成功");
}
if(pStatement.executeUpdate("delete from t_tag where name='测试啊'") != 0){
System.out.println("测试啊删除成功");
}
if (pStatement.executeUpdate("insert into t_tag(id,name,url) values('3','测试啊','hehe')") != 0) {
System.out.println("测试啊添加成功");
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}