62,623
社区成员
发帖
与我相关
我的任务
分享import javax.swing.*;
import java.sql.*;//引入sql包
public class Myjdbc {// 负责连接数据库的类
private static Connection connection = null;// 先定义一个连接为空来连接数据库
private Myjdbc() {
getCon();
}
public static Connection getCon() {
if(connection == null){
try {
Class.forName("com.mysql.jdbc.Driver");// 连接Mysql固定方法
connection = DriverManager
.getConnection("jdbc:mysql://localhost/jxjpd?"
+ "user=root&password=123");
System.out.print("连接成功");
} catch (SQLException ex) {
// 捕捉SQL异常
System.out.println("SQLException: " + ex.getMessage());// 输出各种异常的信息
System.out.println("SQLState: " + ex.getSQLState());
System.out.println("VendorError: " + ex.getErrorCode());
System.out.print("出现SQL异常");
} catch (ClassNotFoundException e) {// 捕获找不到驱动包异常
e.printStackTrace();
System.out.print("出现ClassNotFound异常");
}
}
return connection;
}
}
public class Myjdbc {// 负责连接数据库的类
public static Connection connection = null;// 先定义一个连接为空来连接数据库
static {
getCon();
}
private static void getCon() {
try {
Class.forName("com.mysql.jdbc.Driver");// 连接Mysql固定方法
connection = DriverManager
.getConnection("jdbc:mysql://localhost/jxjpd?"
+ "user=root&password=123");
} catch (SQLException ex) {
// 捕捉SQL异常
System.out.println("SQLException: " + ex.getMessage());// 输出各种异常的信息
System.out.println("SQLState: " + ex.getSQLState());
System.out.println("VendorError: " + ex.getErrorCode());
} catch (ClassNotFoundException e) {// 捕获找不到驱动包异常
e.printStackTrace();
}
}
}