JDBC各个类详解-Statement
执行sql
1.boolean execute(String sql) :可以执行任意sql语句,了解
2.int executeUpdate(String sql) :执行DML(insert update delete)语句,DDL(create alter drop)语句
返回值:影响的行数,可以通过这个影响的行数判断DML语句是否执行成功 返回值>0的则执行成功,反之,则失败
3.ResultSet executeQuery(String sql) :执行DQL(select)语句
JDBC练习-insert语句
account表,添加一条记录
/** * account表,添加一条记录 insert语句 */ public class JDBCDemo02 { public static void main(String[] args) { Connection conn = null; Statement state = null; try { //1.注册驱动 Class.forName("com.mysql.cj.jdbc.Driver"); //2.定义sql String sql = "insert into account values(null,'王五',3000)"; //3.获取Connection对象 conn = DriverManager.getConnection("jdbc:mysql:///db1", "root", "root"); //4.获取执行sql的对象Statement state = conn.createStatement(); //5.执行sql int count = state.executeUpdate(sql);//影响的行数 //6.处理结果 System.out.println(count); if (count>0){ System.out.println("添加成功"); }else { System.out.println("添加失败"); } } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (SQLException e) { e.printStackTrace(); }finally { // state.close(); //7.释放资源 //避免空指针异常 if (state != null){ try { state.close(); } catch (SQLException throwables) { throwables.printStackTrace(); } } if (conn != null){ try { conn.close(); } catch (SQLException throwables) { throwables.printStackTrace(); } } } } }
运行结果: