每日总结

今天进行数据库的连接,在网上搜了很多的代码、模板,但是在自己的电脑上运行的时候总是会出现问题,

搞得我很头痛,即使如此也要静下心来去查找问题,调试问题,解决问题,在网上搜索及向别人请教后,

终于解决了问题,实现了数据库的连接。

代码如下:

public class DBUtil {
private static String url = "jdbc:mysql://localhost:3306/student?useSSL=false&serverTimezone=Asia/Shanghai";
private static String user = "root";
private static String password = "0408";
private static String jdbcName="com.mysql.jdbc.Driver";
private Connection con=null;
public static Connection getConnection() {
Connection con=null;
try {
Class.forName(jdbcName);
con=DriverManager.getConnection(url, user, password);
//System.out.println("数据库连接成功");
} catch (Exception e) {
// TODO Auto-generated catch block
//System.out.println("数据库连接失败");
e.printStackTrace();
}
try {
con = DriverManager.getConnection(url,user,password);
System.out.println("连接成功");


} catch (SQLException e) {
// TODO: handle exception
e.printStackTrace();
}
return con;
}
public static void main(String[] args)throws SQLException {
Connection conn = getConnection();
PreparedStatement pstmt = null;
ResultSet rs = null;
String sql ="select * from student";
pstmt = conn.prepareStatement(sql);
rs = pstmt.executeQuery();
System.out.println(getConnection());
while(rs.next()){
System.out.println("成功!");
}

}

// return con;


public static void close(Connection con) {
if(con!=null)
try {
con.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

}
public static void close(Statement state, Connection conn) {
if(state!=null) {
try {
state.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if(conn!=null) {
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}

public static void close(ResultSet rs, Statement state, Connection conn) {
if(rs!=null) {
try {
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if(state!=null) {
try {
state.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if(conn!=null) {
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}

}

原文地址:https://www.cnblogs.com/lxywsx/p/14186057.html