此 Microsoft SQL Server JDBC Driver 示例应用程序说明了如何使用结果集的 getter 方法来检索基本 SQL Server 数据类型值,以及如何使用结果集的 update 方法来更新这些值。
此示例的代码文件名为 basicDT.java,该文件可在以下位置找到:
<安装目录>\sqljdbc_<版本>\<语言>\help\samples\datatypes
要求
若要运行此示例应用程序,必须将 classpath 设置为包含 sqljdbc.jar 文件或 sqljdbc4.jar 文件。如果 classpath 缺少 sqljdbc.jar 项或 sqljdbc4.jar 项,示例应用程序将引发“找不到类”的常见异常。还需要访问 SQL Server 2005 AdventureWorks 示例数据库。有关如何设置 classpath 的详细信息,请参阅使用 JDBC 驱动程序。
还必须在 SQL Server 2005 AdventureWorks 示例数据库中创建以下表和示例数据:
CREATE TABLE DataTypesTable (Col1 int IDENTITY, Col2 char, Col3 varchar(50), Col4 bit, Col5 decimal(18, 2), Col6 money, Col7 datetime); INSERT INTO DataTypesTable VALUES ('A', 'Some text.', 0, 15.25, 10.00, '01/01/2006 23:59:59.991');
示例
在下面的示例中,示例代码将建立到 SQL Server 2005 AdventureWorks 数据库的连接,然后从 DataTypesTable 测试表中检索一行数据。然后,将调用自定义的 displayRow 方法,以使用 SQLServerResultSet 类的各种 get<Type> 方法来显示结果集中包含的所有数据。
接下来,示例代码使用 SQLServerResultSet 类的各种 update<Type> 方法来更新结果集中包含的数据,然后调用 updateRow 方法将输入更新到数据库中。
最后,示例代码刷新结果集中包含的数据,然后再次调用自定义的 displayRow 方法来显示该结果集中包含的数据。
import java.sql.*; public class basicDT { 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 that returns some data // and display it. String SQL = "SELECT * FROM DataTypesTable;"; stmt = con.createStatement(ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_UPDATABLE); rs = stmt.executeQuery(SQL); rs.next(); displayRow("ORIGINAL DATA", rs); // Update the data in the result set. rs.updateString(2, "B"); rs.updateString(3, "Some updated text."); rs.updateBoolean(4, true); rs.updateDouble(5, 77.89); rs.updateDouble(6, 1000.01); rs.updateTimestamp(7, new Timestamp(System.currentTimeMillis())); rs.updateRow(); // Get the updated data from the database and display it. rs = stmt.executeQuery(SQL); rs.next(); displayRow("UPDATED DATA", rs); } // 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); System.out.println(rs.getInt(1) + " " + // SQL integer type. rs.getString(2) + " " + // SQL char type. rs.getString(3) + " " + // SQL varchar type. rs.getBoolean(4) + " " + // SQL bit type. rs.getDouble(5) + " " + // SQL decimal type. rs.getDouble(6) + " " + // SQL money type. rs.getTimestamp(7)); // SQL datetime type. System.out.println(); } catch (Exception e) { e.printStackTrace(); } } }