Java对数据库的增删查改

xiaoxiao2021-02-28  119

在配置好MySchool库中的所有数据时可利用JavaMySQL中的数据进行一些基本的操作

*查询MySQL中的数据

 

public class Test1 { public static void main(String[] args) throws Exception { // 导入驱动包 Class.forName("com.mysql.jdbc.Driver"); // 链接至数据库 String jdbc = "jdbc:mysql://127.0.0.1:3306/myschool"; Connection conn = DriverManager.getConnection(jdbc, "root", "hbtt"); Statement state = conn.createStatement();// 容器 String sql = "select * from student"; // sql语句 ResultSet rs = state.executeQuery(sql); // 将sql语句传至数据库,返回的值为一个字符集用一个变量接收 while (rs.next()) { // next()获取里面的内容 System.out.println(rs.getString(1) + "\t " + rs.getString(2) + "\t "+ rs.getString(3)); // getString(n)获取第n列的内容 // 数据库中的列数是从1开始的 } conn.close(); } }

 

*修改MySQL中的数据

 

public class Test2 {      public static void main(String[] args) throws Exception {         Class.forName("com.mysql.jdbc.Driver");//加载驱动                  String jdbc="jdbc:mysql://127.0.0.1:3306/myschool";         Connection conn=DriverManager.getConnection(jdbc, "root", "hbtt");//链接到数据库                  Statement state=conn.createStatement();   //容器         String sql="update student set studentName='李四' where studentNo='1001' ";   //SQL语句         state.executeUpdate(sql);         //将sql语句上传至数据库执行         System.out.println("修改成功 !");                  conn.close();//关闭通道     } }

 

*删除MySQL中的数据

 

public class Test3 {      public static void main(String[] args) throws Exception {         Class.forName("com.mysql.jdbc.Driver");//加载驱动                  String jdbc="jdbc:mysql://127.0.0.1:3306/myschool";         Connection conn=DriverManager.getConnection(jdbc, "root", "hbtt");//链接到数据库                  Statement state=conn.createStatement();   //容器         String sql="delete from student where studentNo='1108'";   //SQL语句         state.executeUpdate(sql);         //将sql语句上传至数据库执行         System.out.println("删除成功 ! ");                  conn.close();//关闭通道     } }

 

*增加MySQL中的数据

 

public class Test4 { public static void main(String[] args) throws Exception { Class.forName("com.mysql.jdbc.Driver");// 加载驱动 String jdbc = "jdbc:mysql://127.0.0.1:3306/myschool"; Connection conn = DriverManager.getConnection(jdbc, "root", "hbtt");// 链接到数据库 Statement state = conn.createStatement(); // 容器 String sql = "INSERT  student VALUES(1168,'666666','张四',1,2,'15350858888','北京','1998-10-24 00:00:00','test2@66.com','130521199810248888');"; // SQL语句 state.executeUpdate(sql); // 将sql语句上传至数据库执行 System.out.println("增加成功 ! "); conn.close();// 关闭通道 } }

转载请注明原文地址: https://www.6miu.com/read-40193.html

最新回复(0)