import java.sql.*; public class Database8 { public static void main(String[] args) { Connection conn=null; PreparedStatement ps=null; ResultSet rs=null; try{ Class.forName("com.mysql.cj.jdbc.Driver");//注册驱动 conn=DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/pjpowernode","root","123456");//获取连接 conn.setAutoCommit(false);//关闭事务自动提交机制 ps=conn.prepareStatement("select ename,job,sal from emp"); rs=ps.executeQuery();//处理查询结果集 while(rs.next()){ System.out.println("ename="+rs.getString("ename")+",job="+rs.getString("job")+",sal="+rs.getString("sal")); } conn.commit();//提交事务 }catch (Exception e){ try { conn.rollback();//回滚事务 } catch (SQLException ex) { ex.printStackTrace(); } e.printStackTrace(); }finally {//资源释放 if(rs!=null){ try { rs.close(); } catch (SQLException e) { e.printStackTrace(); } } if(ps!=null){ try { ps.close(); } catch (SQLException e) { e.printStackTrace(); } } if(conn!=null){ try { conn.close(); } catch (SQLException e) { e.printStackTrace(); } } } } }
JDBC编程六步代码实现
最新推荐文章于 2022-12-04 13:31:51 发布