Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package test;
- import java.sql.*;
- public class test { // 下面定义一些全局静态参数,用于数据库连接
- static final String driver = "com.mysql.jdbc.Driver";
- static final String url = "jdbc:mysql://localhost:3306/test";
- static final String user = "root";
- static final String password = "hello";
- public static void main(String[] args) throws SQLException {
- Connection con = null; //创建一个连接对象
- Statement stmt = null; //创建一个语句对象
- ResultSet rs = null;
- try {
- Class.forName(driver);
- con = DriverManager.getConnection(url, user, password); //连接数据库
- con.setAutoCommit(false); // 关掉自动事务递交
- stmt = con.createStatement(); //初始化语句
- String query1 = "update test1 set name ='Shanghai' where id >100";
- String query2 = "update test1 set name ='Beijing' where id >50 and id <90";
- String query3 = "select * from test1 where id >50";
- stmt.executeUpdate(query1);
- stmt.executeUpdate(query2);
- rs = stmt.executeQuery(query3);
- con.commit();
- System.out.println("-----------------");
- System.out.println("执行结果如下所示:");
- System.out.println("-----------------");
- String uid = null;
- String name = null;
- while (rs.next()) {
- //获取stuname这列数据
- uid = rs.getString("id");
- //获取stuid这列数据
- name = rs.getString("name");
- //输出结果
- System.out.println(uid + "\t" + name);
- }
- rs.close(); //关语句
- con.close(); //关连接
- } catch (ClassNotFoundException e) {//如果 JDBC class 找不到捕获抛异常
- //数据库驱动类异常处理
- System.out.println("找不到数据库驱动");
- e.printStackTrace();
- } catch (SQLException e) { // JDBC 层工作中有问题抛异常
- System.err.println("无法连接到数据库");
- e.printStackTrace();
- } catch (Exception e) { // 执行操作有问题抛异常
- con.rollback(); // 失败执行事务回滚
- e.printStackTrace();
- } finally {
- System.out.println("关闭连接");
- if (con !=null) try {con.close(); } catch (SQLException ignore) {} //关闭不掉链接就抛异常
- }
- }
- }
Add Comment
Please, Sign In to add comment