JDBC-Connecion详解注册驱动和Statement详解注册驱动
Connecion详解注册驱动
Connection:数据库连接对象
功能:
- 获取执行sql的对象
Statement createStatement();
PreparedStatement PrepareStatement(String sql)
- 管理事务
开启事务:setAutoCommit(boolean autocommit):调用该方法设置参数为false 即开启事务 提交事务:Commit(); 回滚事务:rollback();
Statement详解注册驱动
statement:执行sql的对象
功能
1.boolean execute(String sql):可以执行任意的sql 2.int ececuteUpdate(String sql):执行DML(insert、update、delete)语句、DDL(create,alter,drop)语句 返回值:影响的行数 可以通过这个影响的行数判断DML语句是否执行成功 返回值>0的则执行成功 反之 则失败 3.ResultSet executeQuery(String sql):执行DQL(select)语句
练习
1.account表 添加一条记录
代码
public static void main(String[] args) { Connection conn = null; Statement stmt = null; try { //1.注册驱动 Class.forName("com.mysql.cj.jdbc.Driver"); //定义SQL语句 String sql = "INSERT INTO account values(null,'王五',3000)"; //获取Connection对象 conn = DriverManager.getConnection("jdbc:mysql:///videopractice", "root", "root"); //获取执行SQL的对象 statement stmt = conn.createStatement(); //执行sql int count = stmt.executeUpdate(sql);//影响的行数 //处理结果 System.out.println(count); if (count > 0) { System.out.println("添加成功!"); } else { System.out.println("添加失败!"); } } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (SQLException throwables) { throwables.printStackTrace(); } finally { if (stmt != null) { try { stmt.close(); } catch (SQLException throwables) { throwables.printStackTrace(); } } if (conn != null) { try { conn.close(); } catch (SQLException throwables) { throwables.printStackTrace(); } } } }
运行结果

SQL数据表

2.account表 删除一条记录
数据表

代码
public static void main(String[] args) { Connection conn = null; Statement stmt = null; try { //1.注册驱动 Class.forName("com.mysql.cj.jdbc.Driver"); //定义SQL语句 String sql = "delete from account where id=4"; //获取Connection对象 conn = DriverManager.getConnection("jdbc:mysql:///videopractice", "root", "root"); //获取执行SQL的对象 statement stmt = conn.createStatement(); //执行sql int count = stmt.executeUpdate(sql);//影响的行数 //处理结果 System.out.println(count); if (count > 0) { System.out.println("删除成功!"); } else { System.out.println("删除失败!"); } } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (SQLException throwables) { throwables.printStackTrace(); } finally { if (stmt != null) { try { stmt.close(); } catch (SQLException throwables) { throwables.printStackTrace(); } } if (conn != null) { try { conn.close(); } catch (SQLException throwables) { throwables.printStackTrace(); } } } }
运行结果

数据库


浙公网安备 33010602011771号