第十四章JDBC.docx
《第十四章JDBC.docx》由会员分享,可在线阅读,更多相关《第十四章JDBC.docx(28页珍藏版)》请在冰豆网上搜索。
第十四章JDBC
第十四章JDBC
14.1ODBC和JDBC
14.2java.sqlpackage简介
14.3准备工作
(1)importjava.sql.*;//导入必要的包
(2)Class.forName(“sun.jdbc.odbc.JdbcOdbcDriver”);//加载适当的驱动程序
(3)利用odbc创建数据源tablesource
(4)创建与数据库的连接
Connectioncon=DriverManager.getConnection(“jdbc:
odbc:
tablesource”);
(5)用con创建语句,执行查询、增删改
Statementstmt=con.CreateStatement();
ResultSetresult=stmt.executeQuery(“select*frommyTable”);
14.4驱动程序管理员-DriveManager类
DriverManager是用来管理驱动程序的类
用Class类的forName方法来加载驱动程序。
可以一次加载多个驱动程序,将来要与数据库连接的时候,DriverManager会根据你的程序挑选适当的驱动程序。
14.4.1DriveManager类的构造函数
没有构造函数,整个程序只需一份DriverManager,他的方法全部是静态的。
14.4.2DriveManager类的方法
publicstaticConnectiongetConnection(Stringurl)throwsSQLException
用url所表示的数据源来创建连接。
url的格式如下:
jdbc:
:
publicstaticConnectiongetConnection(Stringurl,Stringuser,Stringpassword)throwsSQLException
publicstaticEnumerationgetDrivers()
返回所有已经向DriverManager注册过的驱动程序
publicstaticintgetLoginTimeout()
返回驱动程序登录数据库时所能等待的最大时间,以秒为单位
publicstaticvoidsetLoginTimeout()
publicstaticPrintWritergetLogWriter()
返回一个Writer组件,可以将一些信息?
(log)写得输出流中。
Publicstaticvoidprintln(Stringmessage)
用setLogWriter设置的Writer组件将message写到输出流中。
PublicstaticvoidregisterDriver(Driverdriver)throwsSQLException
向DriverManager注册一个数据库驱动程序
publicstaticvoidderegisterDriver(Driverdriver)throwsSQLException
例:
加载JDBC-ODBC驱动程序
importjava.io.*;
importjava.util.*;
importjava.sql.*;
publicclassDriverManagerTest
{
publicstaticvoidmain(Stringargs[])
{
try
{
PrintWriterlogWriter=newPrintWriter(newFileWriter("database.log"));
DriverManager.setLogWriter(logWriter);
try
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
for(Enumeratione=DriverManager.getDrivers();e.hasMoreElements();)
System.out.println(e.nextElement().toString());
DriverManager.println("loadJDBC-ODBCdriversuccessfully.");
}
catch(ClassNotFoundExceptionexcl)
{
DriverManager.println("loadjdbc-odbcdiverfail.");
}
logWriter.close();
}
catch(IOExceptionexc2)
{System.out.println("can'tcreatelogfile.");
}
}
}
14.5Connectioninterface
Connection是DriverManager与数据库之间的桥梁,通过Connection创建Statement,CallableStatement或PreparedStatement组件才能执行SQL某命令。
14.5.1Connectioninterface的方法
publicvoidclose()throwsSQLException
关闭与数据库的连接,同时释放占用的资源
publicStatementcreateStatement()throwsSQLException
创建一个Statement组件,用来执行SQL指令
publicStringgetCatalog()throwsSQLException
返回Connection当前所连接的数据库的实际文件名。
PublicintgetTransactionIsolation()throwsSQLException
返回Connection的isolationlevel。
PublicboolisClosed()throwsSQLException
检查Connection是否已经关闭与数据库的连接
publicboolisReadOnly()throwsSQLException
检查Connection是否为只读状态
publicPreparedStatementprepareStatement(Stringsql)throwsSQLException
创建一个PreparedStatement组件,所执行的指令为sql
publicPreparedStatementpreparestatement(Stringsql,intresultSetType,intresulSetConcurrency)throwsSQLException
创建一个PreparedStatement组件,所执行的指令为sql,并且设置好它将返回的ResultSet组件的特性
例:
importjava.sql.*;
publicclassConnectionTest
{
publicstaticvoidmain(Stringargs[])
{
try
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connectioncon=DriverManager.getConnection("jdbc:
odbc:
tablesource","scott","tiger");
System.out.println(con.getCatalog());
con.close();
}
catch(Exceptione)
{
System.out.println(e);
}
}
}
14.6Statementinterface
Statement是用来执行SQL指令的interface,如果指令返回结果,将产生一个ResulSet。
一个Statement组件一次只能产生一组查询结果(ResultSet),即它只能保留最近产生的结果,如果要想保留两个结果,必须用两个Statement组件。
14.6.1statementinterface的方法
publicvoidcancel()throwsSQLException
取消Statement组件的动作
publicvoidclose()throwsSQLException
释放Statement所占用的资源,释放ResultSet
publicResultSetexecuteQuery(Stringsql)throwsSQLException
执行一个SQL的查询指令,并产生ResultSet
publicintexecuteUpdate(Stringsql)throwsSQLException
执行一个sql的insert,update或delete指令,返回值为插入、删除或更新的数据行数
publicintgetMaxRows()throwsSQLException
返回ResultSet最多能够容纳的数据个数,0代表没有上限。
当sql指令返回的数据个数超过这个值时,多出来的数据会被忽略。
PublicResultSetgetResultSet()throwsSQLException
返回Statement最近所产生的ResultSet。
例:
importjava.sql.*;
publicclassStatementTest
{
publicstaticvoidmain(Stringargs[])
{
try
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connectioncon=DriverManager.getConnection("jdbc:
odbc:
tablesource","scott","tiger");
Statementstmt=con.createStatement();
//创建数据表
stmt.executeUpdate("createtablebooktable(Titlevarchar2(30),authorvarchar2(20),priceinteger)");
//添加两个数据
stmt.executeUpdate("insertintobooktablevalues('datastructure','eric',600)");
stmt.executeUpdate("insertintobooktablevalues('computerDIY','Mr.Lin',500)");
//查询数据
ResultSetresult=stmt.executeQuery("select*frombooktable");
//列出查询结果
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(Exceptione)
{
System.out.println(e);
}
}
}
14.7PreparedStatementinterface继承了Statement的特性,当要执行类似的指令,用?
代替参数,可重复执行。
PreparedStatement
14.7.1PreparedStatementinterface的方法
publicvoidclearParameters()throwsSQLException
将所有的参数清除
publicResultSetexecuteQuery()throwsSQLException
执行查询指令,返回一个ResultSet
publicintexecuteUpdate()throwsSQLException
执行insert、update和delete指令,返回更动的个数
publicvoidsetBoolean(intindex,Booleanx)throwsSQLException
将第index个参数设置成x。
其它类似的还有setByte,setDate,setDouble,setFloat,setInt,setLong,setShort,setString,setTime等,第一个参数代表参数的索引,第二个表示数据类型,index从1开始。
例:
importjava.sql.*;
publicclassPreparedStatementTest
{
publicstaticvoidmain(Stringargs[])
{
String[]title={"Matlab5.3","Linux&xwindow","photoshop5.0"};
String[]author={"Roger","Gao","Sue"};
int[]price={550,530,480};
try
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connectioncon=DriverManager.getConnection("jdbc:
odbc:
tablesource","scott","tiger");
PreparedStatementpstmt=con.prepareStatement("insertintobooktablevalues(?
?
?
)");
//添加三个数据
for(inti=0;i<3;i++)
{
pstmt.setString(1,title[i]);
pstmt.setString(2,author[i]);
pstmt.setInt(3,price[i]);
pstmt.executeUpdate();
}
pstmt.close();
Statementstmt=con.createStatement();
ResultSetresult=stmt.executeQuery("select*frombooktable");
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(Exceptione)
{
System.out.println(e);
}
}
}
14.8ResultSetinterface
ResultSet有两个特性:
光标的移动方式及是否允许数据被更改(concurrency)。
光标的移动方式有:
TYPE_FORWARD_ONLY:
光标只能前进不能后退
TYPE_SCROLL_SENSITIVE:
允许光标前进或后退,会感应到其它ResultSet的光标的移动情形。
TYPE_SCROLL_INSENSITIVE:
允许光标前进或后退,对于其它ResultSet的光标的移动情形感觉不到。
Concurrency有两个常数代表:
CONCUR_READ_ONLY:
表示数据只能只读,不能更改
CONCUR_UPDATEABLE:
表示数据允许被更改
Connection在创建Statement或PreparedStatement时可以加入这两个参数,如:
Statementstmt=con.createStatement(ResultSet.TYPE_FORWARD_ONLY,
ResultSet.CONCUR_READ_ONLY);
或
PreparedStatementstmt=con.createStatement(“insertintobooktablevalues(?
?
?
)”,ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_UPDATABLE);
如果createStatement或prepareStatement没有加那两个参数,默认值为TYPE_FORWARD_ONLY及CONCUR_READ_ONLY。
14.8.1ResultSetinterface的方法
publicvoidclose()throwsSQLException
将ResultSet所占用的资源释放
publicintfindColumn(StringcolumnName)throwsSQLException
找出名称是columnName的字段是位在第几栏,返回值的范围从1开始
publicbooleangetBoolean(intindex)throwsSQLException
返回第index个字段的值,index的范围从1开始。
其它的方法还有:
getByte…
publicbooleannext()throwsSQLException
将ResultSet的光标移到下一个数据上,执行后若光标位在合法的数据上则返回true,若位在最后一个数据的后面则返回false。
一开始,光标在第一个记录的前面。
PublicbooleanwasNull()throwsSQLException
判断最近一次使用getXXX方法所得到的数据是否为SQLNULL。
Publicboolabsolute(introw)throwsSQLException
将光标移到第row个数据上,当row>0,表示移到从第一个数据算起的第row个;若row<0,表示移到从最后一个算上来的第-row个。
PublicvoidafterLast()throwsSQLException
将光标移到最后一个数据的后面
publicvoidbeforeFirst()throwsSQLException
将光标移到第一个数据的前面
publicvoiddeleteRow()throwsSQLException
将ResultSet及数据库中当前这一个数据删除
publicvoidfirst()throwsSQLException
将光标移到到第一个数据上,若成功返回true,否则返回false
publicgetConcurrency()throwsSQLException
返回ResultSet的concurrency属性,可能是CONCUR_READ_ONLY或CONCUR_UPDATABLE。
PublicintgetRow()throwsSQLException
返回当前光标位在第几个数据上,如果在第一个前面或最后一个后面则返回0。
PublicStatementgetStatement()throwsSQLException
返回产生这个ResultSet的Statement,如果ResultSet不是由Statement产生而是由其它方式产生,则返回false.
PublicintgetType()throwsSQLException
返回光标的移动方式,可能是
TYPE_FORWARD_ONLY,
TYPE_SCROLL_INSENSITIVE
或TYPE_SCROLL_SENSITIVE
publicbooleanisAfterLast()throwsSQLException
检查光标是否位在最后一个数据的后面,是则返回true
publicbooleanisFirst()throwsSQLException
检查光标是否在第一个数据上
publicbooleanisBeforeFirst()throwsSQLException
检查光标是否在第一个数据的前面
publicbooleanisLast()throwsSQLException
检查光标是否在最后一个数据上
publicbooleanprevious()throwsSQLException
将光标移到上一个数据上,执行后若光标位在合法的数据上则返回true,若位在第一个数据的前面则返回false
publicbooleanrelative(introws)throwsSQLException
若rows>0则将光标往下移动rows个,若rows<0则将光标往上移动-rows个,如果移动后光标位在合法的数据上则返回true,否则返回false
publicvoidupdateBoolean(intindex,booleanx)throwsSQLException
将当前这个数据的第index个字段的值换成x。
这个方法只会更改到ResultSet中的数据,并不会更改数据库中的数据,除非调用updateRow方法。
其它类似的方法还有updateByte、updateDate、updateDouble….
PublicvoidupdateRow()throwsSQLException
将ResultSet对当前这个数据所做的更改写到数据库里面。
PubliccancelRowUpdates()throwsSQLException
将ResultSet对当前这个数据所做的更改动作通知取消,但如果已经执行过updateRow方法,这个方法就没有作用了。
14.9数据库实例
实例:
学生的成绩记录系统,数据库表格有四个字段:
学生的学号、学生姓名、期中考试成绩与期末考试成绩,类型分别是String,String,Integer与Integer。
用一个Jtable组件来显示数据库中的数据,除了前面四个字段以外,最后又加了一个“平均”的字段表示期末与期中成绩的平均值,此字段不记录在数据库里。
实例程序总共有四个文件,MainFrame.java是主程序、PasswordDialog.java是用来输入账号密码的对话框、AddStudentDialog.java是用来添加学生的对话框、MyTableM