为了账号安全,请及时绑定邮箱和手机立即绑定

java 连接 mysql 数据库

标签:
Java
package com.curtis.mysql.dbc;

import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Properties;

public class DatabaseConnection {

    private static String DRIVER;
    private static String URL;
    private static String USER;
    private static String PASSWORD;

    private Connection connection = null;

    static {
        loadConfig();
    }

    public static void loadConfig() {
        try {
            InputStream inStream = DatabaseConnection.class.getResourceAsStream("/jdbc.properties");
            Properties prop = new Properties();
            prop.load(inStream);
            // System.out.println(prop.toString());
            DRIVER = prop.getProperty("mysql.driver");
            URL = prop.getProperty("mysql.url");
            USER = prop.getProperty("mysql.user");
            PASSWORD = prop.getProperty("mysql.password");
        } catch (Exception e) {
            throw new RuntimeException("读取数据库配置文件异常!", e);
        }
    }

    public Connection getConnection() {
        try {
            Class.forName(DRIVER);
            this.connection = DriverManager.getConnection(URL, USER, PASSWORD);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return connection;
    }

    public void close() {
        if (connection != null) {
            try {
                this.connection.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }

    public static void main(String[] args) {
        DatabaseConnection connection=new DatabaseConnection();
        System.out.println(connection.getConnection());
    }

}
mysql.driver=com.mysql.jdbc.Driver
mysql.url=jdbc:mysql://127.0.0.1:3306/c
mysql.user=root
mysql.password=
点击查看更多内容
1人点赞

若觉得本文不错,就分享一下吧!

评论

作者其他优质文章

正在加载中
感谢您的支持,我会继续努力的~
扫码打赏,你说多少就多少
赞赏金额会直接到老师账户
支付方式
打开微信扫一扫,即可进行扫码打赏哦
今天注册有机会得

100积分直接送

付费专栏免费学

大额优惠券免费领

立即参与 放弃机会
意见反馈 帮助中心 APP下载
官方微信

举报

0/150
提交
取消