首先呢我们可以创建一个Java文件命名为ConnectMySQL.java(你想用什么名字都行),然后呢将它继承App就行了。(VS Code导入jar包需要注意的是,将项目建在盘里,放桌面是绝对不行的)
import java.lang.reflect.InvocationTargetException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.awt.event.ActionEvent;
public class ConnectMySQL extends App{
Connection conn=null;
Statement stmt=null;
ResultSet rs=null;
PreparedStatement prestmt=null;
public ConnectMySQL(){
try {
Class.forName("com.mysql.cj.jdbc.Driver").getDeclaredConstructor().newInstance();
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/库名", "账号", "密码");
} catch (InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException
| NoSuchMethodException | SecurityException | ClassNotFoundException e1) {
e1.printStackTrace();
} catch (SQLException e1) {
e1.printStackTrace();
}
}
public static void main(String[] args) {
}
public void actionPerformed(ActionEvent e){
}
}
创建了连接数据库的方法后怎么使用呢?(见下面的内容)
一名来自北京印刷学院计科的学生