1.首先新建一个项目
2.再新建一个包lib
3.把下好的sql包粘贴到lib里
4.右键lib包点击add as library
结束
DriverManager.registerDriver(new Driver());
String url="jdbc:mysql://127.0.0.1:sql端口号/schooldb?serverTimezone=Asia/Shanghai";
String user="root"; //账户
String password="root"; //密码
Connection connection=DriverManager.getConnection(url,user,password);
Statement statement=connection.createStatement();
statement.executeUpdate("insert into major(name)value('数学')");
statement.close();
connection.close();
插入方法eg:
public static void main(String[] args) throws SQLException {
SqlOperate.insert("lzy","男","1979-4-21","13152113467",1.88);
}
public static void insert(String name,String gender, String birthday,String phone,double height) throws SQLException {
//注册驱动
DriverManager.registerDriver(new Driver());
String url="jdbc:mysql://127.0.0.1:3306/schooldb?serverTimezone=Asia/Shanghai";
String user="root";
String password="root";
//建立与数据库的连接
Connection connection=DriverManager.getConnection(url,user,password);
//发送sql
Statement statement=connection.createStatement();
statement.executeUpdate("update student set name='"+name+"',gender='"+gender+"',birthday='"+birthday+"',phone='"+phone+"',height="+height+"");
//关闭与数据库的连接
statement.close();
connection.close();
}
PreparedStatement ps=connection.prepareStatement("insert into major(name)value(?)"); //?是占位符,表示要插入一个参数
ps.setObject(1,"智能"); //1表示在第一个?位置插入数据
ps.executeUpdate();
PreparedStatement ps=connection.prepareStatement("update student set name=?,gender=?,birthday=?,phone=?,height=? where number=?");
ps.setObject(1,name);
ps.setObject(2,gender);
ps.setObject(3,birthday);
ps.setObject(4,phone);
ps.setObject(5,height);
ps.setObject(6,number);
ps.executeUpdate();