JDBC-ODBC 的過程是 JSP->JDBC->ODBC-DataBase 是以我們要配置ODBC資料源 跟我們指定的資料庫相連接配接
首先我們需要下載下傳一個 JDBC DRIVER FOR SQL SERVER 2008 然後解壓後将.jar檔案放在Tomact的lib 目錄下 或者自己工程的lib目錄下 那麼我們就可以使用
JDBC-通路 SQL SERVER 了 。。
1.使用 JDBC-ODBC加載驅動的方式 Class.ForName("sun.jdbc.odbc.JdbcOdbcDriver") ; //這是JDBC-ODBC連接配接SQL2008的方法 不同的資料庫連接配接方法不同
2. 通路過程中需要 Connection Statement ResultSet 實作了這三個接口的對象 我們通過這三個對象可以完成一個簡單的資料庫通路
Connection c=DriverManager.getConnection("jdbc:odbc:testDatabase","sa","123456") ; //連接配接資料庫傳回Connection的對象
Statement s=c.createStatement() ; //傳回Statement對象 這個對象可以向資料庫發送 SQL查詢
ResultSet r=s.executeQuery("select * from user_table") ; //查詢資料 傳回的結果儲存在ResultSet結果集中
下面是一次簡單的JSP 資料庫通路 :
<%@ page contentType="text/html;charset=GB2312" %>
<%@ page import="java.sql.*" %>
<HTML>
<BODY>
<%
Connection cn ; //資料庫連接配接對象每個對象表示和資料庫的一個連接配接
Statement s ; //Statement 對象将查詢發送到資料庫
ResultSet r ;//查詢結果集的對象 用于Statement傳回的結果
try
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); //首先用Class.Forname()加載驅動使用JDBC-ODBC驅動
}
catch(ClassNotFoundException e)
{
{
cn=DriverManager.getConnection("jdbc:odbc:testDataBase","sa","7603835") ;//通過DriverManager的靜态方法連接配接資料庫并傳回對象
s=cn.createStatement() ;//建立Statement對象可以向伺服器發送SQL查詢語句
r=s.executeQuery("select * from userTable");
while(r.next())
{
out.println(r.getString(4)+"<br>");
}
cn.close() ;
catch(SQLException e)
%>
</BODY>
</HTML>