第一种方法有点麻烦
package com.hp.util;
import java.sql.*;
public class DBHelper {
private static String driver="com.mysql.jdbc.Driver";
private static String url="jdbc:mysql://localhost:3306/usmydb?serverTimezone=Asia/Shanghai";
private static String username="root";
private static String password="123456";
private static Connection conn;
private static PreparedStatement ps;
private static ResultSet rs;
public DBHelper(){}
static {
try {
Class.forName(driver);
System.out.println("驱动链接成功");
} catch (ClassNotFoundException e) {
e.printStackTrace();
System.out.println("驱动链接失败");
}
}
public static Connection getConn(){
try {
conn= DriverManager.getConnection(url,username,password);
System.out.println("链接建立成功");
} catch (SQLException e) {
e.printStackTrace();
}
return conn;
}
public static void close(Connection conn,PreparedStatement ps,ResultSet rs){
{
try {
if(conn!=null)conn.close();
if (ps!=null)ps.close();
if(rs!=null)rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
public static void main(String[] args) {
//输出一下 看数据库是否已连接上
System.out.println(getConn());
}
}
运行效果:
第二种方法比较简便:
package com.hp.util;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class DBHepler {
public static Connection getConn() {
Connection conn= null;
try {
Class.forName("com.mysql.jdbc.Driver");
String url="jdbc:mysql://localhost:3306/usmydb?serverTimezone=Asia/Shanghai";
conn= DriverManager.getConnection(url,"root","123456");
} catch (ClassNotFoundException | SQLException e) {
e.printStackTrace();
}
return conn;
}
//输出看一下是否链接
public static void main(String[] args) {
System.out.println(getConn());
}
}
运行效果: