本文内容
- 复制粘贴,然后运行main文件,快速确定数据库是否能正常连接
- 记得检查是否已经导入驱动jar包
前置知识
package club.test;
import java.sql.*;
public class TestMySQLConnection {
public static void main(String[] args) {
String driver = "com.mysql.jdbc.Driver";
String URL = "jdbc:mysql://localhost:3306/test_2019?useSSL=false";//数据库地址,注意数据库名称.useSSL=false 不加就报一个警告
String username="root";//用户名
String password="123456";//密码
Connection conn = null;
try {
Class.forName(driver);
} catch (java.lang.ClassNotFoundException e) {
System.out.println("Connect Successful.");
System.out.println("Cant't load Driver");
}
try {
conn = DriverManager.getConnection(URL, username, password);
System.out.println("Connect Successful.");
} catch (Exception e) {
System.out.println("Connect fail:" + e.getMessage());
}finally {
try {
conn.close();
} catch (Exception e2) {
System.out.println("Close Connection error.");
}
}
}
}
网友评论