jdbc连接mysql数据库

这个写了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包,仍会抛出异常。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值