JDBC通过Statement执行操作

来源:互联网 发布:linux启动.sh命令 编辑:程序博客网 时间:2024/06/02 08:21

一、通过 JDBC 向指定的数据表中插入一条记录。

1.Statement:用于执行SQL语句的对象

1).通过Connection 的 createStatement()方法来获取

2).通过executeUpdate(sql)可以执行SQL语句

3).传入的SQL可以是INSERT,UPDATE或DELETE,但不能是 SELECT

2.Connection.Statement 就是应用程序和数据库服务器的连接资源,使用后一定要关闭。


二、代码

public static void testStatement() throws Exception{//1.获取数据库连接Connection conn=null;Statement statement = null;try {conn=getConnection2();//3.准备插入的SQL语句String sql="insert into gx values(7,3,4)";//4.执行语句//1).获取操作SQL语句的Statement对象statement = conn.createStatement();//2).调用Statement对象的executeUpdate(sql)执行SQl语句进行操作statement.executeUpdate(sql);} catch (Exception e) {// TODO Auto-generated catch blocke.printStackTrace();}finally{//5.关闭Statement对象try {if(statement!=null)statement.close();} catch (Exception e) {// TODO Auto-generated catch blocke.printStackTrace();}finally{//2.关闭连接if(conn!=null)conn.close();}}}







原创粉丝点击