JDBC 测试连接数据库

JDBC 测试连接数据库

package com.xiang.lesson01;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class DBTest {
/*
**建立连接的五大步骤:**
1. 加载(注册)数据库
2. 建立链接
3. 语句对象来执行SQL语句
4. 处理结果集 、返回结果
5. 关闭数据库、释放资源
*/
//    private static  String URL = "jdbc:mysql://localhost:3307/webapp1?serverTimezone=utf8mb4";
//    useSSL=false 安全连接;
private static  String URL = "jdbc:mysql://localhost:3307/webapp1?serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8&useSSL=false" ;
private  static  String DriverClass ="com.mysql.cj.jdbc.Driver";
private  static  String  UserName ="webapp1";
private  static  String  PassWord ="webapp1";
private  static  Connection connection=null;
public static   Connection getConnection(){
try {
Class.forName(DriverClass);
connection = DriverManager.getConnection(URL,UserName,PassWord);
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
return  connection;
}
//    public  void  closeRerource(Connection connection){
//        try {
//            connection.close();
//        } catch (SQLException throwables) {
//            throwables.printStackTrace();
//        }
//    }
public static void  closeRerource(){
if (connection != null){
try {
connection.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
}
public static void main(String[] args) {
connection = DBTest.getConnection();
if (connection != null){
System.out.println("连接成功");
}else {
System.out.println("连接失败");
}
closeRerource();
}
}

导入mysql jar包

JDBC 测试连接数据库

原文:https://www.cnblogs.com/d534/p/15242231.html

以上是JDBC 测试连接数据库的全部内容。
THE END
分享
二维码
< <上一篇
下一篇>>