Java_jdbc 基础笔记之三 数据库连接 (Statement)

来源:互联网 发布:网络客服的注意事项 编辑:程序博客网 时间:2024/05/18 00:08

/**
* 通过JDBC向之指定的数据表中插入一条记录 1 Statement :用于执行SQL语句的对象
* ==>通过Connection的createStatement()方法来获取 ==>通过executeUpdate(sql)可以执行SQL语句
* ==>传入的SQL可以是INSERT UPDATE DELETE 但不能是SELECT
*
* 2 Connection Statement 都是应用程序数据库服务器的连接资源,使用后一定要关闭
*
*/

@Test    public void testStatement() {        // 1 获取数据库的连接        Connection conn = null;         //2创建用于执行SQL语句的对象        Statement statement = null;        try {            conn = getConnection();            // 3 准备插入SQL 语句            String sql = "INSERT INTO customers(NAME,EMAIL,BIRTH) VALUES('abc','abc@sina.com','1990-12-12')";            // 1)获取操作SQL语句的Statement对象:            // 通过调用 Connection 对象的 createStatement 方法创建该对象            statement = conn.createStatement();            // 2)调用Statement对象的executeUpdate(sql)执行SQL语句进行操作            statement.executeUpdate(sql);        } catch (Exception e) {            e.printStackTrace();        } finally {            //4关闭            if (statement != null) {                try {                    statement.close();                } catch (SQLException e) {                    // TODO Auto-generated catch block                    e.printStackTrace();                }            }            if (conn != null) {                try {                    conn.close();                } catch (SQLException e) {                    // TODO Auto-generated catch block                    e.printStackTrace();                }            }        }    }
0 0
原创粉丝点击