JDBC基础实例

mac2026-04-03  5

package step1; import java.sql.*; public class UpdatePass { // 修改数据 public static void updateDB() { /********* Begin *********/ // 第一步:加载驱动 try { Class.forName("com.mysql.jdbc.Driver"); } catch (ClassNotFoundException ce) { System.out.println("SQLException:" + ce.getMessage()); } Connection con=null; Statement stat=null; try{ // 第二步:建立连接, "root"和"123123"是针对MySQL设置了用户名(root)和密码(123123)的情况 // 127.0.0.1:3306是mysql服务器地址及端口 数据库编码格式设置为utf-8 con = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/tsgc?useUnicode=true&characterEncoding=utf-8", "root", "123123"); // 第三步:建立statement对象 stat = con.createStatement(); // 第四步:修改数据 stat.executeUpdate("update employee set password='hello' where sex='女'"); } catch (SQLException e) { System.out.println("SQLException1:" + e.getMessage()); } // 第五步:关闭statement对象和连接对象 finally { try { if (stat != null) { stat.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(); } } /********* End *********/ } } package step1; import java.sql.*; public class QueryPass { // 查询数据代码不用上实验报告 public static void queryDB() { /********* Begin *********/ // 第一步:加载驱动 try { Class.forName("com.mysql.jdbc.Driver"); } catch (ClassNotFoundException ce) { System.out.println("SQLException:" + ce.getMessage()); } Connection con = null; Statement stat = null; ResultSet rs = null; try{ // 第二步:建立连接, "root"和"123123"是针对MySQL设置了用户名(root)和密码(123123)的情况 // 127.0.0.1:3306是mysql服务器地址及端口 数据库编码格式设置为utf-8 con = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/tsgc?useUnicode=true&characterEncoding=utf-8", "root", "123123"); // 第三步:建立statement对象 stat = con.createStatement(); // 第四步:查询数据 rs = stat.executeQuery("select * from employee"); while (rs.next()) { System.out.println("no:" + rs.getString("no") + "\t" + "name:" + rs.getString("name") + "\t" + "password:" + rs.getString("password") + "\t" + "sex:"+ rs.getString("sex") + "\t" + "salary" + rs.getFloat("salary")); } } catch (SQLException e) { System.out.println("SQLException1:" + e.getMessage()); } // 第五步:关闭statement对象和连接对象 finally { try { if (stat != null) { stat.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(); } } /********* End *********/ } } 李响Superb 认证博客专家 机器学习 TensorFlow 图像处理 成为一名优秀的算法工程师⬆️ ,目前还在读软件工程,AI攻防、算法和深度学习方向,微博同名❤️ :李响Superb,(记得关注,有问题微博私信!)我们一起努力呀!
最新回复(0)