此 Microsoft SQL Server JDBC Driver 示例应用程序说明了如何从 SQL Server 数据库中检索可更新的数据集。然后,它使用 SQLServerResultSet 对象的方法在数据集中插入、修改并最终删除一行数据。
此示例的代码文件名为 updateRS.java,该文件可在以下位置找到:
<安装目录>\sqljdbc_<版本>\<语言>\help\samples\resultsets
要求
若要运行此示例应用程序,必须将 classpath 设置为包含 sqljdbc.jar 文件或 sqljdbc4.jar 文件。如果 classpath 缺少 sqljdbc.jar 项或 sqljdbc4.jar 项,示例应用程序将引发“找不到类”的常见异常。还需要访问 SQL Server 2005 AdventureWorks 示例数据库。有关如何设置 classpath 的详细信息,请参阅使用 JDBC 驱动程序。
示例
在下面的示例中,示例代码将建立与 AdventureWorks 示例数据库的连接。然后,该代码使用了具有 SQLServerStatement 对象的 SQL 语句,它运行该 SQL 语句,将其返回的数据放入可更新的 SQLServerResultSet 对象中。
接下来,示例代码使用 moveToInsertRow 方法将结果集游标移动到要插入的行,使用一系列 updateString 方法将数据插入新行,然后调用 insertRow 方法将新数据行添加回数据库中。
插入新的数据行后,示例代码使用 SQL 语句检索前面插入的行,然后同时使用 updateString 和 updateRow 方法更新数据行,并再次将其添加回数据库中。
最后,示例代码检索前面已更新的数据行,然后使用 deleteRow 方法将其从数据库中删除。
import java.sql.*; public class updateRS { public static void main(String[] args) { // Create a variable for the connection string. String connectionUrl = "jdbc:sqlserver://localhost:1433;" + "databaseName=AdventureWorks;integratedSecurity=true;"; // Declare the JDBC objects. Connection con = null; Statement stmt = null; ResultSet rs = null; try { // Establish the connection. Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver"); con = DriverManager.getConnection(connectionUrl); // Create and execute an SQL statement, retrieving an updateable result set. String SQL = "SELECT * FROM HumanResources.Department;"; stmt = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE); rs = stmt.executeQuery(SQL); // Insert a row of data. rs.moveToInsertRow(); rs.updateString("Name", "Accounting"); rs.updateString("GroupName", "Executive General and Administration"); rs.updateString("ModifiedDate", "08/01/2006"); rs.insertRow(); // Retrieve the inserted row of data and display it. SQL = "SELECT * FROM HumanResources.Department WHERE Name = 'Accounting';"; rs = stmt.executeQuery(SQL); displayRow("ADDED ROW", rs); // Update the row of data. rs.first(); rs.updateString("GroupName", "Finance"); rs.updateRow(); // Retrieve the updated row of data and display it. rs = stmt.executeQuery(SQL); displayRow("UPDATED ROW", rs); // Delete the row of data. rs.first(); rs.deleteRow(); System.out.println("ROW DELETED"); } // Handle any errors that may have occurred. catch (Exception e) { e.printStackTrace(); } finally { if (rs != null) try { rs.close(); } catch(Exception e) {} if (stmt != null) try { stmt.close(); } catch(Exception e) {} if (con != null) try { con.close(); } catch(Exception e) {} } } private static void displayRow(String title, ResultSet rs) { try { System.out.println(title); while (rs.next()) { System.out.println(rs.getString("Name") + " : " + rs.getString("GroupName")); System.out.println(); } } catch (Exception e) { e.printStackTrace(); } } }