这个写了n次,每次写每次忘。
所以打算重新写好并记录下来。
1 . 搭好环境
mysql+navicate+eclipse+tomcat
2 . 将数据库相关的jar包放到 lib 文件夹下,并且build path 中调好配置
3 .主体代码分为两部分
(1) db.properties 这是数据库的配置文件
user=root
url=jdbc:mysql://localhost:3306/graduation_test
password=admin
driver=com.mysql.jdbc.Driver
user 和 password 表示 mysql 数据库建立的时候连接的名字和密码
url 指的是数据库所在的路径,graduation_test 是数据库的名字
(2) DBConnection.java
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.Properties;
public class DBConnection {
private static String user;
private static String password;
private static String url;
//静态代码块,实现程序一开始运行就加载配置文件
static {
try {
ClassLoader classLoader = DBConnection.class.getClassLoader();
InputStream is = classLoader.getResourceAsStream("./db.properties");
Properties props = new Properties();
props.load(is);
url = props.getProperty("url");
user = props.getProperty("user");
password = props.getProperty("password");
// 注册驱动
Class.forName(props.getProperty("driver"));
} catch (ClassNotFoundException e) {
e.printStackTrace();
throw new RuntimeException("找不到驱动");
} catch (IOException e) {
e.printStackTrace();
throw new RuntimeException("加载properites文件错误");
}
}
// 获取连接
public static Connection getConnection() throws Exception {
return DriverManager.getConnection(url, user, password);
}
// 关闭连接有结果集(select)
public static void close(ResultSet rs, Statement stat, Connection conn)
throws Exception {
if (rs != null) {
rs.close();
}
if (stat != null) {
stat.close();
}
if (conn != null) {
conn.close();
}
}
// 关闭连接无结果集(delete update insert)
public static void close(Statement stat, Connection conn) throws Exception {
if (stat != null) {
stat.close();
}
if (conn != null) {
conn.close();
}
}
//在main函数中测试是否连接成功
//测试方法:
//直接调用getConnection()方法,如果连接成功则会成功运行getConnection()方//法,并接着运行Syso语句。否则会直接抛出异常。
public static void main(String[] args) {
try {
getConnection();
System.out.println("连接成功!");
} catch (Exception e) {
e.printStackTrace();
}
}
}
//显示”连接成功!”则表示连接成功
//直接运行这个java文件就行,不用在服务器上跑。
经过测试,如果url 、user 、或者password不对,则会抛出异常
若提前没有加入数据库驱动 jar包,仍会抛出异常。