首先先下载MySQL驱动jar包
链接: Connector/J.、
1、新建完项目之后
idea右上角
找到jar包的路径
就可以了,然后就可以开始写代码了
import java.math.BigInteger;
import java.util.Calendar;
import java.util.Scanner;
import java.util.concurrent.CancellationException;
import java.sql.*;
public class Main { //最基本的连接
public static void main(String[] args) {
Scanner cin = new Scanner(System.in);
Connection con;
//连接的路径,test是我的数据库名
String url = "jdbc:mysql://localhost:3306/test?useSSL=false&serverTimezone=UTC";
String user = "root"; //访问的用户
String pw = "123456"; //密码
try {
con = DriverManager.getConnection(url,user,pw);
if(!con.isClosed()) {
System.out.println("succeed");
}
con.close();
}catch (ClassCastException e) {
System.out.println("asdwfeghjkahgks");
}catch (SQLException e) {
e.printStackTrace();
System.out.println("defeat..");
}
}
}
package Link_Database;
import java.math.BigInteger;
import java.util.Calendar;
import java.util.Scanner;
import java.util.concurrent.CancellationException;
import java.sql.*;
public class Main {
public static void main(String[] args) {
Scanner cin = new Scanner(System.in);
Connection con;
String url = "jdbc:mysql://localhost:3306/test?useSSL=false&serverTimezone=UTC";
String user = "root";
String pw = "123456";
try {
Statement st = con.createStatement();
PreparedStatement ins = con.prepareStatement("insert into student(na) value(?);");
PreparedStatement del = con.prepareStatement("delete from student where na=?;");
del.setString(1,"Apple"); //传入sql语句中?的位置,1表示第一个问好,如果还有问号就2,3,4
del.execute(); //execute函数执行sql语句
ResultSet ans = st.executeQuery("select * from student"); //返回一个结果集合(每一行)
while(ans.next()) { //遍历结果
System.out.println(ans.getString("na")); //输出当前行列名位na的值
}
con.close();
}catch (ClassCastException e) {
System.out.println("asdwfe");
}catch (SQLException e) {
e.printStackTrace();
System.out.println("defeat..");
}
}
}