1.查询(7步)
Connection con = null; // 创建一个connection Statement stmr=null; ResultSet ret=null; String driver="com.mysql.cj.jdbc.Driver"; //这里我的数据库是jdbctest String url="jdbc:mysql://localhost:3306/jdbctest?&useSSL=false&serverTimezone=UTC"; String user="root"; String password="123456"; Connection conn=null; try { //1.加载驱动 Class.forName(driver); //2.创建连接 conn = DriverManager.getConnection(url, user, password); if (!con.isClosed()) { System.out.println("数据库连接成功"); } } catch (Exception e) { e.printStackTrace(); } try { //3.写sql语句 String sql="select id,name,number,school from student"; //4.得到statement对象 stmr = con.createStatement(); //5.执行sql语句 ret=stmr.executeQuery(sql); //6.处理结果集 while(ret.next()){ int id=ret.getInt("id"); String name=ret.getString("name"); String number=ret.getString("number"); String school=ret.getString("school"); System.out.println(id+" "+name+" "+number+" "+school); } catch(SQLException e){ e.printStackTrace(); } finally { //7.关闭资源 if(ret!=null) try { ret.close(); }catch (SQLException e){ e.printStackTrace(); } if(ste!=null) try { ste.close(); }catch (SQLException e){ e.printStackTrace(); } if(con!=null) try { con.close(); }catch (SQLException e){ e.printStackTrace(); } }
2.插入数据
String strsql="insert into student values(4,'Maven','123123','加用')"; stmr.execute(strsql);
3.删除数据
String desql="delete from student where id='1'"; stmr.execute(desql);
4.修改数据
String altersql="update student set id='9' where id='3'"; stmr.execute(altersql);