首先将MySQL\Connector J 8.0\mysql-connector-java-8.0.27.jar 导入
如何导入如下图
后续操作如下
package text;
import java.sql.*;
import java.util.Collection;
public class Demo1 {
public static void main(String args[]) {
String URL="jdbc:mysql://localhost:3306/db"; //db为数据库的名字
String USER="root";
String PASSWORD="root"; //自己设置的数据库的密码
Statement sta=null;
Connection con=null;
try {
//1.加载数据库驱动
Class.forName("com.mysql.jdbc.Driver"); //mysql-connector-java-8.0.27.jar中找到com.mysql.jdbc-->右键Driver.class-->copy qualified Name获得“com.mysql.jdbc.Driver”
//2.建立数据库连接
con=DriverManager.getConnection(URL,USER,PASSWORD);
sta =con.createStatement();
//3.执行SQL语句
String sql="insert into s values(1,'zz',9)"; //s为表的名字
int count =sta.executeUpdate(sql);
//4.处理结果
if(count>0) {
System.out.print("数据库连接成功");
}
else {
System.out.print("数据库连接不成功,请重试");
}
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//5.关闭数据库集
finally {
try {
if(sta!=null)
sta.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
if(con!=null)
con.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}