利用mvc架构写简单的图书馆管理系统—数据库的链接
package com.anbow.manager.util;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class DBUtil {
public static Connection getConnection(){
String name="root";
//MySQL配置时的用户名
String pwd="123456";
//MySQL配置时的用户名
String url="jdbc:mysql://localhost:3306/bookmanager";
//url指向要访问的数据库名mydata
Connection conn=null;
//声明Connection对象
//遍历查询的结果集
try {
//加载驱动程序
Class.forName("com.mysql.jdbc.Driver");
//1.getConnection()方法,连接MySQL数据库
conn=DriverManager.getConnection(url, name, pwd);
} catch (ClassNotFoundException e) {
//数据库驱动类异常处理
// TODO: handle exception
e.printStackTrace();
} catch (SQLException e) {
//数据库连接失败异常处理
// TODO Auto-generated catch block
e.printStackTrace();
}
return conn;
}
public static void closeConnection(Connection conn){
if(conn!=null){
try {
conn.close();
} catch (SQLException e) {
// TODO: handle exception
e.printStackTrace();
}
}
}
public static void main(String[] args){
if(getConnection()!=null){
System.out.println("ok");
}else{
System.out.println("error");
}
}
}