jdbc连接数据库(mysql)

驱动包

使用 mysql-connector-java-5.X.jar 版本的驱动包,连接 mysql5.6、mysql5.7

连接数据库

mysql5.7

String driver="com.mysql.jdbc.Driver";
String url="jdbc:mysql://127.0.0.1:3306/scott?useSSL=false&useUnicode=true&characterEncoding=utf-8";
String username="root";
String password="123456";

//加载驱动
Class.forName(driver);
//创建数据库连接
Connection conn=DriverManager.getConnection(url, username, password);
if(conn!=null && !conn.isClosed()){
    System.out.println("连接成功!");
}

mysql5.6

String driver="com.mysql.jdbc.Driver";
String url="jdbc:mysql://127.0.0.1:3306/scott";
String username="root";
String password="123456";

//加载驱动
Class.forName(driver);
//创建数据库连接
Connection conn=DriverManager.getConnection(url, username, password);
if(conn!=null && !conn.isClosed()){
    System.out.println("连接成功!");
}

将数据库信息写在配置文件中

数据库ip、port、库名、用户名、密码可能会发生变化,写死在代码中不合理,所以要写在配置文件中

创建文件 db.properties ,内容如下:

driver=com.mysql.cj.jdbc.Driver
url=jdbc:mysql://127.0.0.1:3306/scott?useSSL=false&useUnicode=true&characterEncoding=utf-8
user=root
password=123456

读取配置文件

FileInputStream fis = new FileInputStream(filename);
Properties p = new Properties();
p.load(fis);
String url = p.getProperty("url");
String user = p.getProperty("user");
String password = p.getProperty("password");
String driver = p.getProperty("driver");

连接数据库

String sql="SELECT id,username,PASSWORD FROM user";

Connection conn=null;
try {
    //加载驱动
    Class.forName(driver);//非运行时异常(检查异常),必须要做处理
    //注册驱动,其实不需要写,在Driver类中,已经注册好了

    conn=DriverManager.getConnection(url,username,password);
    if(conn!=null && !conn.isClosed()){
        System.out.println("数据库连接成功!");
    }


} catch (ClassNotFoundException e) {
    e.printStackTrace();
} catch (SQLException throwables) {
    throwables.printStackTrace();
} finally {
    try {
        if(conn!=null && !conn.isClosed()){
            conn.close();
            System.out.println("关闭数据库连接!");
        }
    } catch (SQLException throwables) {
        throwables.printStackTrace();
    }
}

原文出处:/show_1IX12VYKDIBU.html