JDBC(六)

来源:互联网 发布:java xbootclasspath 编辑:程序博客网 时间:2024/05/11 11:33

JDBC Statement对象实例

以下是利用以下三种查询以及打开和关闭说明的例子:

  • boolean execute(String SQL) : 返回一个布尔值true,如果ResultSet对象可以被检索,否则返回false。使用这个方法来执行SQL DDL语句,或当需要使用真正的动态SQL。

  • int executeUpdate(String SQL) : 返回受影响的SQL语句执行的行数。使用此方法来执行,而希望得到一些受影响的行的SQL语句 - 例如,INSERT,UPDATE或DELETE语句。

  • ResultSet executeQuery(String SQL) : 返回ResultSet对象。当希望得到一个结果集使用此方法,就像使用一个SELECT语句。







基于对环境和数据库安装在前面的章节中做此示例代码已被写入。

复制下面的例子中JDBCExample.java,编译并运行,如下所示:

//STEP 1. Import required packagesimport java.sql.*;public class JDBCExample {   // JDBC driver name and database URL   static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";     static final String DB_URL = "jdbc:mysql://localhost/EMP";   //  Database credentials   static final String USER = "username";   static final String PASS = "password";      public static void main(String[] args) {   Connection conn = null;   Statement stmt = null;   try{      //STEP 2: Register JDBC driver      Class.forName("com.mysql.jdbc.Driver");      //STEP 3: Open a connection      System.out.println("Connecting to database...");      conn = DriverManager.getConnection(DB_URL,USER,PASS);      //STEP 4: Execute a query      System.out.println("Creating statement...");      stmt = conn.createStatement();      String sql = "UPDATE Employees set age=30 WHERE id=103";            // Let us check if it returns a true Result Set or not.      Boolean ret = stmt.execute(sql);      System.out.println("Return value is : " + ret.toString() );      // Let us update age of the record with ID = 103;      int rows = stmt.executeUpdate(sql);      System.out.println("Rows impacted : " + rows );      // Let us select all the records and display them.      sql = "SELECT id, first, last, age FROM Employees";      ResultSet rs = stmt.executeQuery(sql);      //STEP 5: Extract data from result set      while(rs.next()){         //Retrieve by column name         int id  = rs.getInt("id");         int age = rs.getInt("age");         String first = rs.getString("first");         String last = rs.getString("last");         //Display values         System.out.print("ID: " + id);         System.out.print(", Age: " + age);         System.out.print(", First: " + first);         System.out.println(", Last: " + last);      }      //STEP 6: Clean-up environment      rs.close();      stmt.close();      conn.close();   }catch(SQLException se){      //Handle errors for JDBC      se.printStackTrace();   }catch(Exception e){      //Handle errors for Class.forName      e.printStackTrace();   }finally{      //finally block used to close resources      try{         if(stmt!=null)            stmt.close();      }catch(SQLException se2){      }// nothing we can do      try{         if(conn!=null)            conn.close();      }catch(SQLException se){         se.printStackTrace();      }//end finally try   }//end try   System.out.println("Goodbye!");}//end main}//end JDBCExample

现在编译上面的例子如下:

C:>javac JDBCExample.javaC:>

当运行JDBCExample,它会产生以下结果:

C:>java JDBCExampleConnecting to database...Creating statement...Return value is : falseRows impacted : 1ID: 100, Age: 18, First: Zara, Last: AliID: 101, Age: 25, First: Mahnaz, Last: FatmaID: 102, Age: 30, First: Zaid, Last: KhanID: 103, Age: 30, First: Sumit, Last: MittalGoodbye!C:>

本教程介绍了如何使用JDBC应用程序数据库的例子。执行下面的示例之前,请确保已到位如下:

  • 应该有管理员特权,在给定的模式创建一个数据库。执行下面的例子中,需要与实际用户名和密码代替用户名和密码。

  • MySQL或者其他数据库,正在使用的是启动和运行。

所需的步骤:






有创建使用JDBC应用程序一个新的数据库需要执行以下步骤:

  • 导入数据包 . 要求包括含有需要进行数据库编程的JDBC类的包。大多数情况下,使用导入的java.sql.* 就足够了。

  • 注册JDBC驱动程序 . 要求初始化驱动程序,使可以与数据库打开一个通信通道。

  • 打开连接 . 要求使用DriverManager.getConnection()方法创建一个Connection对象,它代表datbase服务器的物理连接。

    要创建一个新的数据库,不用给任何数据库名,同时准备数据库URL中所提到的下面的例子。

  • 执行查询. 需要使用类型声明的对象建立并提交一个SQL语句到数据库。

  • 清理环境. 需要明确地关闭所有的数据库资源与依靠JVM垃圾收集。

示例代码:











复制下面的例子中JDBCExample.java,编译并运行,如下所示:

//STEP 1. Import required packagesimport java.sql.*;public class JDBCExample {   // JDBC driver name and database URL   static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";     static final String DB_URL = "jdbc:mysql://localhost/";   //  Database credentials   static final String USER = "username";   static final String PASS = "password";      public static void main(String[] args) {   Connection conn = null;   Statement stmt = null;   try{      //STEP 2: Register JDBC driver      Class.forName("com.mysql.jdbc.Driver");      //STEP 3: Open a connection      System.out.println("Connecting to database...");      conn = DriverManager.getConnection(DB_URL, USER, PASS);      //STEP 4: Execute a query      System.out.println("Creating database...");      stmt = conn.createStatement();            String sql = "CREATE DATABASE STUDENTS";      stmt.executeUpdate(sql);      System.out.println("Database created successfully...");   }catch(SQLException se){      //Handle errors for JDBC      se.printStackTrace();   }catch(Exception e){      //Handle errors for Class.forName      e.printStackTrace();   }finally{      //finally block used to close resources      try{         if(stmt!=null)            stmt.close();      }catch(SQLException se2){      }// nothing we can do      try{         if(conn!=null)            conn.close();      }catch(SQLException se){         se.printStackTrace();      }//end finally try   }//end try   System.out.println("Goodbye!");}//end main}//end JDBCExample

现在让我们来编译上面的例子如下:

C:>javac JDBCExample.javaC:>

当运行JDBCExample,它会产生以下结果:

C:>java JDBCExampleConnecting to database...Creating database...Database created successfully...Goodbye!C:>

本教程介绍了如何使用JDBC应用程序选择一个数据库的例子。执行下面的示例之前,请确保已做好如下工作:

  • 执行下面的例子中,需要使用实际用户名和密码代替username和password。

  • MySQL或者其他数据库,正在使用(启动和运行)。

所需的步骤:






创建使用JDBC应用程序访问数据库需要执行以下步骤:

  • 导入数据包 . 要求包括含有需要进行数据库编程的JDBC类包。大多数情况下,使用 import java.sql.*就足够了。

  • 注册JDBC驱动程序 . 要求初始化驱动程序,从而可以与数据库打开一个通信通道。

  • 打开连接. 使用DriverManager.getConnection()方法创建一个Connection对象,它代表使用所选(selected)数据库的物理连接。

    选择数据库时,准备数据库URL。下面的例子会让STUDENTS数据库连接。

  • 清理环境. 需要明确地关闭所有的数据库资源相对依靠JVM的垃圾收集。

示例代码:










复制下面的例子中JDBCExample.java,编译并运行,如下所示:

//STEP 1. Import required packagesimport java.sql.*;public class JDBCExample {   // JDBC driver name and database URL   static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";     static final String DB_URL = "jdbc:mysql://localhost/STUDENTS";   //  Database credentials   static final String USER = "username";   static final String PASS = "password";      public static void main(String[] args) {   Connection conn = null;   try{      //STEP 2: Register JDBC driver      Class.forName("com.mysql.jdbc.Driver");      //STEP 3: Open a connection      System.out.println("Connecting to a selected database...");      conn = DriverManager.getConnection(DB_URL, USER, PASS);      System.out.println("Connected database successfully...");   }catch(SQLException se){      //Handle errors for JDBC      se.printStackTrace();   }catch(Exception e){      //Handle errors for Class.forName      e.printStackTrace();   }finally{      //finally block used to close resources      try{         if(conn!=null)            conn.close();      }catch(SQLException se){         se.printStackTrace();      }//end finally try   }//end try   System.out.println("Goodbye!");}//end main}//end JDBCExample

现在来编译上面的例子如下:

C:>javac JDBCExample.javaC:>

当运行JDBCExample,它会产生以下结果:

C:>java JDBCExampleConnecting to a selected database...Connected database successfully...Goodbye!C:>

本教程介绍了如何使用JDBC应用程序来删除一个现有数据库的例子。执行下面的示例之前,请确保如下:

  • 执行下面的例子中,需要使用实际用户名和密码代替username和password。

  • MySQL或者其他数据库,正在使用:启动和运行。




注意:这是一个严重的操作,数据库中拥有的一切将会丢失。

所需步骤:



有创建使用JDBC应用程序一个新的数据库需要执行以下步骤:

  • 导入数据包:要求包括含有需要进行数据库编程的JDBC类的包。大多数情况下,使用 import java.sql.* 就可以了.

  • 注册JDBC驱动程序:要求初始化驱动程序,使它可以与数据库打开一个通信通道。

  • 打开一个连接:要求中使用DriverManager.getConnection()方法创建一个Connection对象,它代表与数据库服务器的物理连接。

    删除一个数据库不需要数据库名称在数据库URL。下面的例子将删除STUDENTS数据库。

  • 执行查询: 需要使用类型声明的对象建立并提交一个SQL语句来删除数据库。

  • 清理环境. 需要明确地关闭所有的数据库资源相对依靠JVM的垃圾收集。

示例代码:











复制下面的例子中JDBCExample.java,编译并运行,如下所示:

//STEP 1. Import required packagesimport java.sql.*;public class JDBCExample {   // JDBC driver name and database URL   static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";     static final String DB_URL = "jdbc:mysql://localhost/";   //  Database credentials   static final String USER = "username";   static final String PASS = "password";      public static void main(String[] args) {   Connection conn = null;   Statement stmt = null;   try{      //STEP 2: Register JDBC driver      Class.forName("com.mysql.jdbc.Driver");      //STEP 3: Open a connection      System.out.println("Connecting to a selected database...");      conn = DriverManager.getConnection(DB_URL, USER, PASS);      System.out.println("Connected database successfully...");            //STEP 4: Execute a query      System.out.println("Deleting database...");      stmt = conn.createStatement();            String sql = "DROP DATABASE STUDENTS";      stmt.executeUpdate(sql);      System.out.println("Database deleted successfully...");   }catch(SQLException se){      //Handle errors for JDBC      se.printStackTrace();   }catch(Exception e){      //Handle errors for Class.forName      e.printStackTrace();   }finally{      //finally block used to close resources      try{         if(stmt!=null)            conn.close();      }catch(SQLException se){      }// do nothing      try{         if(conn!=null)            conn.close();      }catch(SQLException se){         se.printStackTrace();      }//end finally try   }//end try   System.out.println("Goodbye!");}//end main}//end JDBCExample

现在让我们来编译上面的例子如下:

C:>javac JDBCExample.javaC:>

当运行JDBCExample,它会产生以下结果:

C:>java JDBCExampleConnecting to a selected database...Connected database successfully...Deleting database...Database deleted successfully...Goodbye!C:>


0 0