JDBC添加数据
数据库连接的类型是 Connection 类型, 如果要操作数据库还需要使用该对象来发送 sql语句
Connection 的方法:
viod close() throws SQLExection
关闭数据库连接, 数据库连接使用完毕之后必须关闭
boolean isClosed() throws SQL Exection
判断该连接是否关闭
void commit() throws SQLExection
在程序中手工提交事务
void rollback() throws SQLExection
事务的回退
void setAutoCommit(boolean autoCommit) throws SQLExection
在 mysql 的 JDBC 中事务是自动提交的, 如果不需要事务自动提交则可以使用该方法进行设置
设置为false 则表示取消自动提交
Statement create Statement() throws SQLExection
取得一个发送 sql 语句的接口对象, 但是现在不是哦用该接口对象来发送 sql 语句了,
因为该接口存在一定的性能问题以及安全问题 (比如 sql 语句注入风险), 效率也低
sql 注入:sql 注入是多年前的一个概念了, 就是可以通过 sql 注入的方式实现无密码的操作
PreparedStatement preparedStatement(String sql)
取得一个发送 sql 语句的接口对象,该对象的类型就是 PreparedStatement 接口,其他第三方数据层工具封装也是该接口,
该接口可以避免类似于 sql注入 的安全风险问题, 并且效率更高 (现在程序中将 sql 语句编译成指令后再发送到数据库,
数据库只需要直接执行指令即可)
PreparedStatement 中的发送 sql 语句的方法:
ResultSet executeQuery( ) throws SQLExection
执行查询语句,将查询到的结果封装到 ResultSet 接口对象中
int executeUpdate( ) throws SQLExection
执行的是更新类型 (insert, update, delete) 的 sql 语句, 返回值的是成功更新数据的条数)
Demo: 定义插入数据的程序
public class TestMysql { //取得连接 private static Connection conn =ConnectionUitl.getConnection(); public static void main(String[] args) { System.out.println("插入的数据行数是: " + insertEmp()); } public static int insertEmp() { PreparedStatement pst = null; //定义出 sql 语句 String sql = "INSERT INTO emp(empno,ename,job,sal,hiredate,mgr,comm,deptno)" +" VALUES(1002,'王五','总裁',9000.00,NOW(),7788,2000.00,10)"; //使用连接对象取得发送 sql 语句的对象 (PreparedStatment 接口对象) try { conn.setAutoCommit(false); //取消事务的自动提交 pst = conn.prepareStatement(sql); //发送 sql 语句 return pst.executeUpdate(); } catch (SQLException e) { e.printStackTrace(); } finally { ConnectionUitl.close(conn,pst); } return 0; } }
Demo: 手动提交事务
1 public class TestMysql { 2 //取得连接 3 private static Connection conn =ConnectionUitl.getConnection(); 4 5 public static void main(String[] args) { 6 System.out.println("插入的数据行数是: " + insertEmp()); 7 } 8 9 public static int insertEmp() { 10 int affectRow = 0; 11 12 PreparedStatement pst = null; 13 14 //定义出 sql 语句 15 String sql = "INSERT INTO emp(empno,ename,job,sal,hiredate,mgr,comm,deptno)" 16 +" VALUES(1002,'王五','总裁',9000.00,NOW(),7788,2000.00,10)"; 17 18 //使用连接对象取得发送 sql 语句的对象 (PreparedStatment 接口对象) 19 try { 20 conn.setAutoCommit(false); //取消事务的自动提交 21 pst = conn.prepareStatement(sql); 22 //发送 sql 语句(手动提交事务) 23 affectRow = pst.executeUpdate(); 24 conn.commit(); 25 return affectRow; 26 } catch (SQLException e) { 27 e.printStackTrace(); 28 } finally { 29 ConnectionUitl.close(conn,pst); 30 } 31 return 0; 32 } 33 }