PrepJDBC.java~7~
资源名称:某公司的java培训教材 [点击查看]
上传用户:dinglihq
上传日期:2013-02-04
资源大小:99958k
文件大小:2k
源码类别:
Java编程
开发平台:
Java
- package com.cwj.DatabaseAccessDemo;
- //以下例子演示PreparedStatement的使用
- import java.sql.*;
- public class PrepJDBC {
- public PrepJDBC() {
- Connection conn=null;
- Statement stat1=null;
- Statement stat2=null;
- ResultSet result=null;
- PreparedStatement pstmt;
- String sqlString="create table digest("+
- "id int not null CONSTRAINT pk_id PRIMARY KEY CLUSTERED,"+
- "author varchar(20), titile varchar(50))";
- String insertSQL = "Insert INTO digest VALUES(?, ?, ?)" ;
- int[] ids = {1, 2, 3, 4, 5} ;
- String[] authors = {"java", "rjb", "java", "bill", "scott"} ;
- String[] titles = { "Prepared Hello",
- "Prepared Hello Java",
- "Prepared Hello Robert",
- "Prepared Hello from Bill",
- "Prepared Hello from Scott"} ;
- try{
- Class.forName("com.microsoft.jdbc.sqlserver.SQLServerDriver");
- conn=DriverManager.getConnection("jdbc:microsoft:sqlserver://127.0.0.1;DatabaseName=Northwind;User=sa;Password=sa");
- stat1=conn.createStatement();
- //创建表结构
- stat1.executeUpdate(sqlString);
- //通过循环向表中添加数据
- pstmt = conn.prepareStatement(insertSQL) ;
- for(int i = 0 ; i < ids.length ; i++){
- pstmt.setInt(1, ids[i]) ;
- pstmt.setString(2, titles[i]) ;
- pstmt.setString(3, authors[i]) ;
- pstmt.executeUpdate() ;
- }
- stat2=conn.createStatement();
- //检查刚才插入的记录
- result=stat2.executeQuery("Select * from book");
- System.out.println("编号"+" "+"作者"+" "+"书名");
- while(result.next()){
- System.out.println(result.getString(1)+" "+result.getString(2)+" "+result.getString(3));
- }
- if(result!=null){
- result.close();
- }
- if(stat1!=null){
- stat1.close();
- }
- if(stat2!=null){
- stat2.close();
- }
- if(pstmt!=null){
- pstmt.close();
- }
- if(conn!=null){
- conn.close();
- }
- }catch(Exception e){
- System.out.println("Error"+e);
- }
- }
- }