JDBC 通过 Statement 执行更新操作

// 通过Statement 向表中插入一条记录(update、delete可以通过调用Statement对象的executeUpdate()方法来执行对应的删除和更新操作)
class MyTest{
     // 获取数据库连接
    public Connection myConnection() throws Exception{
        String driverClass = "com.mysql.jdbc.Driver";
        String jdbcUrl = "jdbc:mysql://localhost:3306/mydb";
        String user = "user";
        String password = "password";

        Class.forName(driverClass);
        Connection connection= DriverManager.getConnection(jdbcUrl,user,password);
        return connection;
     }     
    public void myStatement() throws SQLException{
        Connection conn = null;
        Statement statement = null;
        try{
            // 1. 获取数据库连接
            conn = myConnection();
            // 2. 准备执行的SQL
            String sql = "Insert into table(name,email,birth) values('xyz','[email protected]','xxxx-xx-xx')";
            // 3. 执行SQL(注意执行的SQL可以是INSERT、UPDATE或DELETE。但不能是SELECT)
            // 1)获取操作SQL语句的Statement对象
            // 通过调用Connection的createStatement()方法来获取
            statement = conn.createStatement()'
            // 2)调用Statement对象的executeUpdate(sql)执行SQL语句进行插入
            statement.executeUpdate(sql);
        }catch(Exception e){
             e.printStackTrace();
        }finally{
              // 关闭Statement对象
              if(statement != null){
                  try{
                      statement.close()
                  }catch(Exception e2){
                      e2.printStackTrace();
                  }
              }
              // 关闭连接
              if(conn != null){
                  try{
                      conn.close()
                  }catch(Exception e2){
                      e2.printStackTrace();
                  }
              }        
        }
    }
}    

你可能感兴趣的:(JDBC 通过 Statement 执行更新操作)