import java.sql.*; public class AccEmpl{ public static void main(String[] args){ //对象变量说明 Connection con; //数据库连接对象(代表与某一数据库的连接) Statement stmt; //语句对象(可接受和执行一条SQL语句) ResultSet rs; //结果集对象(保存查询返回的结果) String sql; //加载数据库驱动程序 DriverManager.registerDriver(new com.mysql.jdbc.driver); //建立一个与数据库的连接 con = DriverManager.getConnection("jdbc:mysql:employee"); //创建一个statement对象 stmt = con.createStatement(); System.out.println("--------查询所有职工 ,按出生年月排序---------"); //执行查询 rs = stmt.executeQuery("SELECT * FROM emp ORDER BY birthday"); while(rs.next()){ System.out.print(rs.getString("ename") + " "); System.out.println(rs.getDate("birthday")); } System.out.println("-----统计并显示各部门职工数-----"); sql = "SELECT departmentNo, COUNT(*) FROM emp Group By departmentNo"; rs = stmt.executeQuery(sql); while(rs.next()){ System.out.print(rs.getInt(1) + " "); System.out.println(rs.getInt(2)); } System.out.println("----------插入一条职工记录------------"); sql = "INSERT INTO emp VALUES(‘e01‘,‘Lin‘,‘male‘,‘1990-01-22‘,1000)"; stmt.executeUpdate(sql); System.out.println("-----------修改职工的工资----------"); sql = "UPDATE emp SET sal=sal+? WHERE eno = ?"; PreparedStatement ps = con.prepareStatement(sql); ps.setInt(1, 200); ps.setString(2, "e10"); ps.executeUpdate(); con.commit(); //提交修改 con.close(); //结束一个会话周期 } }
时间: 2024-11-03 22:26:33