第十四章JDBC
14.1 ODBC和JDBC
14.2 java.sql package简介
14.3 准备工作
(1)import java.sql.*; //导入必要的包(2)Class.forName(“sun.jdbc.odbc.JdbcOdbcDriver”); //加载适当的驱动程序
(3)利用odbc创建数据源tablesource
(4)创建与数据库的连接
Connection
con=DriverManager.getConnection(“jdbc:odbc:tables ource”);
(5)用con创建语句,执行查询、增删改
Statement stmt=con.CreateStatement();
ResultSet result=stmt.executeQuery(“select * from myTable”);
14.4 驱动程序管理员-DriveManager类
DriverManager是用来管理驱动程序的类
用Class类的forName方法来加载驱动程序。可以一次加载多个驱动程序,将来要与数据库连接的时候,DriverManager会根据你的程序挑选适当的驱动
程序。
14.4.1 DriveManager类的构造函数
没有构造函数,整个程序只需一份DriverManager,他的方法全部是静态的。
14.4.2 DriveManager 类的方法
public static Connection getConnection(String url) throws SQLException
用url所表示的数据源来创建连接。url的格式如下:
jdbc:
public static Connection getConnection(String url,String user,String password) throws SQLException
public static Enumeration getDrivers()
返回所有已经向DriverManager注册过的驱动程序
public static int getLoginTimeout()
返回驱动程序登录数据库时所能等待的最大时间,以秒为单位
public static void setLoginTimeout()
public static PrintWriter getLogWriter()
返回一个Writer组件,可以将一些信息?(log)写得输出流中。
Public static void println(String message)
用setLogWriter设置的Writer组件将message 写到输出流中。
Public static void registerDriver(Driver driver) throws SQLException
向DriverManager注册一个数据库驱动程序
public static void deregisterDriver(Driver driver) throws SQLException
例:加载JDBC-ODBC驱动程序
import java.io.*;
import java.util.*;
import java.sql.*;
public class DriverManagerTest
public static void main(String args[])
{
try
{
PrintWriter logWriter=new PrintWriter(new FileWriter("database.log"));
DriverManager.setLogWriter(logWriter);
try
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
for (Enumeration e=DriverManager.getDrivers();e.hasMoreElements(); )
System.out.println(e.nextElement().toString());
DriverManager.println("load JDBC-ODBC driver successfully.");
}
catch (ClassNotFoundException excl)
{
DriverManager.println("load
jdbc-odbc diver fail.");
}
logWriter.close();
}
catch (IOException exc2)
{ System.out.println("can't create log file.");
}
}
}
14.5 Connection interface
Connection是DriverManager与数据库之间的桥梁,通过Connection创建Statement,CallableStatement或PreparedStatement组件才能执
行SQL某命令。
14.5.1 Connection interface的方法
public void close() throws SQLException
关闭与数据库的连接,同时释放占用的资源
public Statement createStatement() throws SQLException
创建一个Statement组件,用来执行SQL指令
public String getCatalog() throws SQLException 返回Connection当前所连接的数据库的实际文件名。
Public int getTransactionIsolation() throws SQLException
返回Connection的isolation level。
Public bool isClosed() throws SQLException
检查Connection是否已经关闭与数据库的连接
public bool isReadOnly() throws SQLException 检查Connection是否为只读状态
public PreparedStatement prepareStatement(String sql) throws SQLException 创建一个PreparedStatement组件,所执行的指令为sql
public PreparedStatement preparestatement(String sql, int resultSetType, int resulSetConcurrency) throws SQLException 创建一个PreparedStatement组件,所执行的指令为sql,并且设置好它将返回的ResultSet组件的特性例:
import java.sql.*;
public class ConnectionTest
{
public static void main(String args[])
{
try
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection
con=DriverManager.getConnection("jdbc:odbc:table source","scott","tiger");
System.out.println(con.getCatalog());
con.close();
}
catch (Exception e)
{
System.out.println(e);
}
}
}
14.6 Statement interface
Statement是用来执行SQL指令的interface,如果指令返回结果,将产生一个ResulSet。一个Statement 组件一次只能产生一组查询结果(ResultSet),即它只能保留最近产生的结果,如果要想保留两个结果,必须用两个Statement组件。
14.6.1 statement interface的方法
public void cancel() throws SQLException
取消Statement组件的动作
public void close()throws SQLException
释放Statement所占用的资源,释放ResultSet
public ResultSet executeQuery(String sql) throws SQLException
执行一个SQL的查询指令,并产生ResultSet
public int executeUpdate(String sql) throws SQLException
执行一个sql的insert,update或delete指令,返回值为插入、删除或更新的数据行数
public int getMaxRows()throws SQLException
返回ResultSet最多能够容纳的数据个数,0代表没有上限。当sql指令返回的数据个数超过这个值时,多出来的数据会被忽略。
Public ResultSet getResultSet()throws
SQLException
返回Statement最近所产生的ResultSet。
例:
import java.sql.*;
public class StatementTest
{
public static void main(String args[])
{
try
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection
con=DriverManager.getConnection("jdbc:odbc:table source","scott","tiger");
Statement stmt=con.createStatement();
//创建数据表
stmt.executeUpdate("create table booktable (Title varchar2(30),author varchar2(20),price integer)");
//添加两个数据
stmt.executeUpdate("insert into
booktable values('data structure','eric',600)");
stmt.executeUpdate("insert into booktable values('computer DIY','Mr.Lin',500)");
//查询数据
ResultSet
result=stmt.executeQuery("select * from booktable");
//列出查询结果
System.out.println("Title\t\tauthor\tPrice");
System.out.println("====================");
while (result.next())
{
System.out.print(result.getString(1)+"\t");
System.out.print(result.getString(2)+"\t");
System.out.println(result.getInt(3));
}
stmt.close();
con.close();
}
catch (Exception e)
{
System.out.println(e);
}
}
}
14.7 PreparedStatement interface继承了Statement的特性,当要执行类似的指令,用?代替参数,可重复执行。
PreparedStatement
14.7.1 PreparedStatement interface的方法
public void clearParameters() throws SQLException
将所有的参数清除
public ResultSet executeQuery()throws SQLException
执行查询指令,返回一个ResultSet
public int executeUpdate() throws SQLException
执行insert、update和delete指令,返回更动的个数
public void setBoolean(int index,Boolean x) throws SQLException
将第index个参数设置成x。其它类似的还有setByte,setDate,setDouble,setFloat,setInt,setLong,setShort,setString,setTime等,第一个参数代表参数的索引,第二个表示数据类型,index从1开始。
例:
import java.sql.*;
public class PreparedStatementTest
{
public static void main(String args[])
{
String[] title={"Matlab 5.3","Linux &xwindow","photoshop 5.0"};
String[] author={"Roger","Gao","Sue"};
int[] price={550,530,480};
try
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection
con=DriverManager.getConnection("jdbc:odbc:table source","scott","tiger");
PreparedStatement
pstmt=con.prepareStatement("insert into booktable values(?,?,?)");
//添加三个数据
for (int i=0;i<3;i++)
{
pstmt.setString(1,title[i]);
pstmt.setString(2,author[i]);
pstmt.setInt(3,price[i]);
pstmt.executeUpdate();
}
pstmt.close();
Statement stmt=con.createStatement();
ResultSet
result=stmt.executeQuery("select * from booktable"); System.out.println("Title\t\tauthor\tPrice");
System.out.println("====================");
while (result.next())
{
System.out.print(result.getString(1)+"\t");
System.out.print(result.getString(2)+"\t");
System.out.println(result.getInt(3));
}
stmt.close();
con.close();
}
catch (Exception e)
{
System.out.println(e);
}
}
}
14.8 ResultSet interface
ResultSet有两个特性:光标的移动方式及是否允许数据被更改(concurrency)。
光标的移动方式有:
TYPE_FORWARD_ONLY:光标只能前进不能后
退
TYPE_SCROLL_SENSITIVE:允许光标前进或后退,会感应到其它ResultSet的光标的移动情形。
TYPE_SCROLL_INSENSITIVE:允许光标前进或后退,对于其它ResultSet的光标的移动情形感觉不到。
Concurrency有两个常数代表:
CONCUR_READ_ONLY:表示数据只能只读,不能更改
CONCUR_UPDATEABLE:表示数据允许被更改Connection在创建Statement或PreparedStatement 时可以加入这两个参数,如:
Statement
stmt=con.createStatement(ResultSet.TYPE_FORWA RD_ONLY,
ResultSet.CONCUR_READ_ONLY);
或
PreparedStatement
stmt=con.createStatement(“insert into booktable values(?,?,?)”,ResultSet.TYPE_SCROLL_INSENSIT
IVE,ResultSet.CONCUR_UPDATABLE);
如果createStatement或prepareStatement没有加那两个参数,默认值为TYPE_FORWARD_ONLY及CONCUR_READ_ONLY。
14.8.1 ResultSet interface的方法
public void close() throws SQLException
将ResultSet所占用的资源释放
public int findColumn(String columnName) throws SQLException
找出名称是columnName的字段是位在第几栏,返回值的范围从1开始
public boolean getBoolean(int index) throws SQLException
返回第index个字段的值,index的范围从1开始。其它的方法还有:getByte…
public boolean next() throws SQLException
将ResultSet的光标移到下一个数据上,执行后若
光标位在合法的数据上则返回true,若位在最后一个数据的后面则返回false。一开始,光标在第一个记录的前面。
Public boolean wasNull() throws SQLException 判断最近一次使用getXXX方法所得到的数据是否为SQL NULL。
Public bool absolute(int row) throws SQLException
将光标移到第row个数据上,当row>0,表示移到从第一个数据算起的第row个;若row<0,表示移到从最后一个算上来的第-row个。
Public void afterLast() throws SQLException
将光标移到最后一个数据的后面
public void beforeFirst() throws SQLException 将光标移到第一个数据的前面
public void deleteRow() throws SQLException
将ResultSet及数据库中当前这一个数据删除
public void first() throws SQLException
将光标移到到第一个数据上,若成功返回true,否则返回false
public getConcurrency() throws SQLException 返回ResultSet的concurrency属性,可能是CONCUR_READ_ONLY或CONCUR_UPDATABLE。
Public int getRow() throws SQLException
返回当前光标位在第几个数据上,如果在第一个前面或最后一个后面则返回0。
Public Statement getStatement() throws SQLException
返回产生这个ResultSet的Statement,如果ResultSet不是由Statement产生而是由其它方式产生,则返回false.
Public int getType() throws SQLException
返回光标的移动方式,可能是
TYPE_FORWARD_ONLY,
TYPE_SCROLL_INSENSITIVE
或TYPE_SCROLL_SENSITIVE
public boolean isAfterLast() throws SQLException
检查光标是否位在最后一个数据的后面,是则返回true
public boolean isFirst() throws SQLException
检查光标是否在第一个数据上
public boolean isBeforeFirst() throws SQLException
检查光标是否在第一个数据的前面
public boolean isLast() throws SQLException
检查光标是否在最后一个数据上
public boolean previous() throws SQLException 将光标移到上一个数据上,执行后若光标位在合法的数据上则返回true,若位在第一个数据的前