日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問(wèn) 生活随笔!

生活随笔

當(dāng)前位置: 首頁(yè) > 编程语言 > java >内容正文

java

[Java]jdbc[转]

發(fā)布時(shí)間:2025/6/17 java 46 豆豆
生活随笔 收集整理的這篇文章主要介紹了 [Java]jdbc[转] 小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
[Java]jdbc[轉(zhuǎn)]

?

>>http://www.cnblogs.com/xiohao/p/3507483.html

>>http://www.cnblogs.com/hongten/archive/2011/03/29/1998311.html

>>http://www.cnblogs.com/lee/archive/2007/08/25/869656.html

JDBC連接各種數(shù)據(jù)庫(kù)方法

1)連接Oracle 8/8i/9i/10g/11g(thin模式)Class.forName("oracle.JDBC.driver.OracleDriver").newInstance();String url="JDBC:oracle:thin:@localhost:1521:orcl" //orcl為Oracle數(shù)據(jù)庫(kù)的SID String user="test";String password="test";Connection con=DriverManager.getConnection(url,user,password);2)連接DB2數(shù)據(jù)庫(kù)Class.forName("com.ibm.db2.jcc.DB2Driver");String url="JDBC:db2://localhost:5000/testDb";String user="test"; String password="test";Connection con=DriverManager.getConnection(url,user,password);3)連接MySQL數(shù)據(jù)庫(kù)Class.forName("com.mysql.jdbc.Driver");String url="JDBC:mysql://localhost:8080/testDB";String user="test"; String password="test";Connection con=DriverManager.getConnection(url,user,password);4)連接SQL Server2000數(shù)據(jù)庫(kù)Class.forName("com.microsoft.JDBC.sqlserver.SQLServerDriver");String url="JDBC:microsoft:sqlserver://localhost:1433;DatabaseName=testDb";String user="test"; String password="test";Connection con=DriverManager.getConnection(url,user,password);5)連接PostgreSQL數(shù)據(jù)庫(kù)Class.forName("org.postgresql.Driver");String url="JDBC:postgresql://localhost/testDb";String user="test"; String password="test";Connection con=DriverManager.getConnection(url,user,password);6)連接Access數(shù)據(jù)庫(kù)Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");String url="JDBC:odbc:Driver={Microsoft Access Driver (*.mdb)};DBQ="+application.getRealPath("/Data/testDb/mdb");Connection conn=DriverManager.getConnection(url,"","");7連接Sybase數(shù)據(jù)庫(kù)Class.forName("com.sybase.JDBC.SybDriver");String url="JDBC:sybase:Tds:localhost:5007/testDb";Properties pro=System.getProperties();pro.put("user","userId");pro.put("password","user_password");Connection con=DriverManager.getConnection(url,pro);8連接informix數(shù)據(jù)庫(kù)Class.forName("com.informix.JDBC.ifxDriver");String url="JDBC:informix-sqli:localhost:1533/testDb:INFORMIXSERVER=myserver"user=testUser;password=testpassword"; Connection con=DriverManager.getConnection(url);

完整java開(kāi)發(fā)中JDBC連接數(shù)據(jù)庫(kù)代碼和步驟

JDBC連接數(shù)據(jù)庫(kù) ?創(chuàng)建一個(gè)以JDBC連接數(shù)據(jù)庫(kù)的程序,包含7個(gè)步驟1、加載JDBC驅(qū)動(dòng)程序: 在連接數(shù)據(jù)庫(kù)之前,首先要加載想要連接的數(shù)據(jù)庫(kù)的驅(qū)動(dòng)到JVM(Java虛擬機(jī)), 這通過(guò)java.lang.Class類的靜態(tài)方法forName(String className)實(shí)現(xiàn)。 例如: try{ //加載MySql的驅(qū)動(dòng)類 Class.forName("com.mysql.jdbc.Driver") ; }catch(ClassNotFoundException e){ System.out.println("找不到驅(qū)動(dòng)程序類 ,加載驅(qū)動(dòng)失敗!"); e.printStackTrace() ; } 成功加載后,會(huì)將Driver類的實(shí)例注冊(cè)到DriverManager類中。 2、提供JDBC連接的URL ?連接URL定義了連接數(shù)據(jù)庫(kù)時(shí)的協(xié)議、子協(xié)議、數(shù)據(jù)源標(biāo)識(shí)。 ?書寫形式:協(xié)議:子協(xié)議:數(shù)據(jù)源標(biāo)識(shí) 協(xié)議:在JDBC中總是以jdbc開(kāi)始 子協(xié)議:是橋連接的驅(qū)動(dòng)程序或是數(shù)據(jù)庫(kù)管理系統(tǒng)名稱。 數(shù)據(jù)源標(biāo)識(shí):標(biāo)記找到數(shù)據(jù)庫(kù)來(lái)源的地址與連接端口。 例如:(MySql的連接URL) jdbc:mysql: //localhost:3306/test?useUnicode=true&characterEncoding=gbk ; useUnicode=true:表示使用Unicode字符集。如果characterEncoding設(shè)置為 gb2312或GBK,本參數(shù)必須設(shè)置為true 。characterEncoding=gbk:字符編碼方式。 3、創(chuàng)建數(shù)據(jù)庫(kù)的連接 ?要連接數(shù)據(jù)庫(kù),需要向java.sql.DriverManager請(qǐng)求并獲得Connection對(duì)象, 該對(duì)象就代表一個(gè)數(shù)據(jù)庫(kù)的連接。 ?使用DriverManager的getConnectin(String url , String username , String password )方法傳入指定的欲連接的數(shù)據(jù)庫(kù)的路徑、數(shù)據(jù)庫(kù)的用戶名和 密碼來(lái)獲得。 例如: //連接MySql數(shù)據(jù)庫(kù),用戶名和密碼都是root String url = "jdbc:mysql://localhost:3306/test" ; String username = "root" ; String password = "root" ; try{ Connection con = DriverManager.getConnection(url , username , password ) ; }catch(SQLException se){ System.out.println("數(shù)據(jù)庫(kù)連接失敗!"); se.printStackTrace() ; } 4、創(chuàng)建一個(gè)Statement ?要執(zhí)行SQL語(yǔ)句,必須獲得java.sql.Statement實(shí)例,Statement實(shí)例分為以下3 種類型: 1、執(zhí)行靜態(tài)SQL語(yǔ)句。通常通過(guò)Statement實(shí)例實(shí)現(xiàn)。 2、執(zhí)行動(dòng)態(tài)SQL語(yǔ)句。通常通過(guò)PreparedStatement實(shí)例實(shí)現(xiàn)。 3、執(zhí)行數(shù)據(jù)庫(kù)存儲(chǔ)過(guò)程。通常通過(guò)CallableStatement實(shí)例實(shí)現(xiàn)。 具體的實(shí)現(xiàn)方式: Statement stmt = con.createStatement() ; PreparedStatement pstmt = con.prepareStatement(sql) ; CallableStatement cstmt = con.prepareCall("{CALL demoSp(? , ?)}") ; 5、執(zhí)行SQL語(yǔ)句 Statement接口提供了三種執(zhí)行SQL語(yǔ)句的方法:executeQuery 、executeUpdate 和execute 1、ResultSet executeQuery(String sqlString):執(zhí)行查詢數(shù)據(jù)庫(kù)的SQL語(yǔ)句 ,返回一個(gè)結(jié)果集(ResultSet)對(duì)象。 2、int executeUpdate(String sqlString):用于執(zhí)行INSERT、UPDATE或 DELETE語(yǔ)句以及SQL DDL語(yǔ)句,如:CREATE TABLE和DROP TABLE等 3、execute(sqlString):用于執(zhí)行返回多個(gè)結(jié)果集、多個(gè)更新計(jì)數(shù)或二者組合的 語(yǔ)句。 具體實(shí)現(xiàn)的代碼: ResultSet rs = stmt.executeQuery("SELECT * FROM ...") ; int rows = stmt.executeUpdate("INSERT INTO ...") ; boolean flag = stmt.execute(String sql) ; 6、處理結(jié)果 兩種情況: 1、執(zhí)行更新返回的是本次操作影響到的記錄數(shù)。 2、執(zhí)行查詢返回的結(jié)果是一個(gè)ResultSet對(duì)象。 ? ResultSet包含符合SQL語(yǔ)句中條件的所有行,并且它通過(guò)一套get方法提供了對(duì)這些 行中數(shù)據(jù)的訪問(wèn)。 ? 使用結(jié)果集(ResultSet)對(duì)象的訪問(wèn)方法獲取數(shù)據(jù): while(rs.next()){ String name = rs.getString("name") ; String pass = rs.getString(1) ; // 此方法比較高效 } (列是從左到右編號(hào)的,并且從列1開(kāi)始) 7、關(guān)閉JDBC對(duì)象 操作完成以后要把所有使用的JDBC對(duì)象全都關(guān)閉,以釋放JDBC資源,關(guān)閉順序和聲 明順序相反: 1、關(guān)閉記錄集 2、關(guān)閉聲明 3、關(guān)閉連接對(duì)象 if(rs != null){ // 關(guān)閉記錄集 try{ rs.close() ; }catch(SQLException e){ e.printStackTrace() ; } } if(stmt != null){ // 關(guān)閉聲明 try{ stmt.close() ; }catch(SQLException e){ e.printStackTrace() ; } } if(conn != null){ // 關(guān)閉連接對(duì)象 try{ conn.close() ; }catch(SQLException e){ e.printStackTrace() ; } }

?

?

jdbc

什么是JDBC? Java語(yǔ)言訪問(wèn)數(shù)據(jù)庫(kù)的一種規(guī)范,是一套API JDBC (Java Database Connectivity) API,即Java數(shù)據(jù)庫(kù)編程接口,是一組標(biāo)準(zhǔn)的Java語(yǔ)言中的接口和類,使用這些接口和類,Java客戶端程序可以訪問(wèn)各種不同類型的數(shù)據(jù)庫(kù)。比如建立數(shù)據(jù)庫(kù)連接、執(zhí)行SQL語(yǔ)句進(jìn)行數(shù)據(jù)的存取操作。JDBC規(guī)范采用接口和實(shí)現(xiàn)分離的思想設(shè)計(jì)了Java數(shù)據(jù)庫(kù)編程的框架。接口包含在java.sql及javax.sql包中,其中java.sql屬于JavaSE,javax.sql屬于JavaEE。這些接口的實(shí)現(xiàn)類叫做數(shù)據(jù)庫(kù)驅(qū)動(dòng)程序,由數(shù)據(jù)庫(kù)的廠商或其它的廠商或個(gè)人提供。為了使客戶端程序獨(dú)立于特定的數(shù)據(jù)庫(kù)驅(qū)動(dòng)程序,JDBC規(guī)范建議開(kāi)發(fā)者使用基于接口的編程方式,即盡量使應(yīng)用僅依賴java.sql及javax.sql中的接口和類。JDBC驅(qū)動(dòng)程序: 什么是JDBC驅(qū)動(dòng)程序? 這些是各個(gè)數(shù)據(jù)庫(kù)廠家根據(jù)JDBC的規(guī)范制作的JDBC實(shí)現(xiàn)類 JDBC驅(qū)動(dòng)程序的四種類型: 1. 第一種類型的驅(qū)動(dòng)程序的實(shí)現(xiàn)是通過(guò)將JDBC的調(diào)用全部委托給其它編程接口來(lái)實(shí)現(xiàn)的,比如ODBC。這種類型的驅(qū)動(dòng)程序需要安裝本地代碼庫(kù),即依賴于本地的程序,所以便攜性較差。比如JDBC-ODBC橋驅(qū)動(dòng)程序 2. 第二種類型的驅(qū)動(dòng)程序的實(shí)現(xiàn)是部分基于Java語(yǔ)言的。即該驅(qū)動(dòng)程序一部分是用Java語(yǔ)言編寫,其它部分委托本地的數(shù)據(jù)庫(kù)的客戶端代碼來(lái)實(shí)現(xiàn)。同類型1的驅(qū)動(dòng)一樣,該類型的驅(qū)動(dòng)程序也依賴本地的程序,所以便攜性較差 3. 第三種類型的驅(qū)動(dòng)程序的實(shí)現(xiàn)是全部基于JAVA語(yǔ)言的。該類型的驅(qū)動(dòng)程序通常由某個(gè)中間件服務(wù)器提供,這樣客戶端程序可以使用數(shù)據(jù)庫(kù)無(wú)關(guān)的協(xié)議和中間件服務(wù)器進(jìn)行通信,中間件服務(wù)器再將客戶端的JDBC調(diào)用轉(zhuǎn)發(fā)給數(shù)據(jù)庫(kù)進(jìn)行處理 4. 第四種類型的驅(qū)動(dòng)程序的實(shí)現(xiàn)是全部基于JAVA語(yǔ)言的。該類型的驅(qū)動(dòng)程序中包含了特定數(shù)據(jù)庫(kù)的訪問(wèn)協(xié)議,使得客戶端可以直接和數(shù)據(jù)庫(kù)進(jìn)行通信JDBC類結(jié)構(gòu):DriverManagerDriver DriverConnection ConnectionStatement StatementResultset ResultsetDriverManager:這個(gè)是一個(gè)實(shí)現(xiàn)類,它是一個(gè)工廠類,用來(lái)生產(chǎn)Driver對(duì)象的 這個(gè)類的結(jié)構(gòu)設(shè)計(jì)模式為工廠方法 Driver:這是驅(qū)動(dòng)程序?qū)ο蟮慕涌?它指向一個(gè)實(shí)實(shí)在在的數(shù)據(jù)庫(kù)驅(qū)動(dòng)程序?qū)ο?那么這個(gè)數(shù)據(jù)庫(kù)驅(qū)動(dòng)程序?qū)ο笫菑哪睦飦?lái)的呢? DriverManager工廠中有個(gè)方法:getDriver(String URL),通過(guò)這個(gè)方法可以得到驅(qū)動(dòng)程序?qū)ο?這個(gè)方法是在各個(gè)數(shù)據(jù)庫(kù)廠商按JDBC規(guī)范設(shè)計(jì)的數(shù)據(jù)庫(kù)驅(qū)動(dòng)程序包里的類中靜態(tài)實(shí)現(xiàn)的,也就是在靜態(tài)塊中 Connection:這個(gè)接口可以制向一個(gè)數(shù)據(jù)庫(kù)連接對(duì)象,那么如何得到這個(gè)連接對(duì)象呢? 是通過(guò)DriverManager工廠中的getConnection(String URL)方法得到的 Statement:用于執(zhí)行靜態(tài)的SQL語(yǔ)句的接口,通過(guò)Connection中的createStatement方法得到的 Resultset:用于指向結(jié)果集對(duì)象的接口,結(jié)果集對(duì)象是通過(guò)Statement中的execute等方法得到的JAVA使用JDBC訪問(wèn)數(shù)據(jù)庫(kù)的步驟: 1. 得到數(shù)據(jù)庫(kù)驅(qū)動(dòng)程序 2. 創(chuàng)建數(shù)據(jù)庫(kù)連接 3. 執(zhí)行SQL語(yǔ)句 4. 得到結(jié)果集 5. 對(duì)結(jié)果集做相應(yīng)的處理(增,刪,改,查) 6. 關(guān)閉資源:這里釋放的是DB中的資源設(shè)置classpath: 1. 在java文件中起的包名一定要是工程基目錄下的子目錄,classpath:基目錄 2. .jar包,需要將這個(gè).jar包的路徑包括這個(gè)文件的全名添加到classpath中來(lái) Oracle連接字符串的書寫格式: “oracle:jdbc:thin:@ip:1521: 數(shù)據(jù)庫(kù)名”,”數(shù)據(jù)庫(kù)用戶名”,”數(shù)據(jù)庫(kù)密碼”簡(jiǎn)單的例子: package moudule1.first;import java.sql.*;public class FirstJdbc {public static void main(String[] args){String sql="select * from yuchen_user";Connection con=null;Statement st=null;ResultSet rs=null;try{ Class.forName("oracle.jdbc.driver.OracleDriver");con=DriverManager.getConnection("jdbc:oracle:thin:@127.0.0.1:1521:name", "scott","tiger");st=con.createStatement();rs=st.executeQuery(sql);while(rs.next()){System.out.println(rs.getInt("id"));System.out.println(rs.getString("name"));}}catch(Exception e){e.printStackTrace();}finally{try{con.close();}catch(Exception e){}try{st.close();}catch(Exception e){}try{rs.close();}catch(Exception e){}}}}常用數(shù)據(jù)庫(kù)的驅(qū)動(dòng)程序及JDBC URL: Oracle數(shù)據(jù)庫(kù): 驅(qū)動(dòng)程序包名:ojdbc14.jar 驅(qū)動(dòng)類的名字:oracle.jdbc.driver.OracleDriverJDBC URL:jdbc:oracle:thin:@dbip:port:databasename說(shuō)明:驅(qū)動(dòng)程序包名有可能會(huì)變JDBC URL中黑色字體部分必須原封不動(dòng)的保留,為該驅(qū)動(dòng)識(shí)別的URL格式。紅色字體部分需要根據(jù)數(shù)據(jù)庫(kù)的安裝情況填寫。其中各個(gè)部分含義如下:dbip –為數(shù)據(jù)庫(kù)服務(wù)器的IP地址,如果是本地可寫:localhost或127.0.0.1。port –為數(shù)據(jù)庫(kù)的監(jiān)聽(tīng)端口,需要看安裝時(shí)的配置,缺省為1521。databasename –為數(shù)據(jù)庫(kù)的SID,通常為全局?jǐn)?shù)據(jù)庫(kù)的名字。舉例如果要訪問(wèn)本地的數(shù)據(jù)庫(kù)allandb,端口1521,那么URL寫法如下:jdbc:oracle:thin:@localhost:1521:allandb 下載地址如下: http://www.oracle.com/technology/software/tech/java/sqlj_jdbc/index.html

SQL Server數(shù)據(jù)庫(kù)驅(qū)動(dòng)程序包名:msbase.jar mssqlserver.jar msutil.jar驅(qū)動(dòng)類的名字:com.microsoft.jdbc.sqlserver.SQLServerDriverJDBC URL:jdbc:microsoft:sqlserver://dbip:port;DatabaseName=databasename 說(shuō)明:驅(qū)動(dòng)程序包名有可能會(huì)變JDBC URL中黑色字體部分必須原封不動(dòng)的保留,為該驅(qū)動(dòng)識(shí)別的URL格式。紅色字體部需要根據(jù)數(shù)據(jù)庫(kù)的安裝情況填寫。其中各個(gè)部分含義如下:dbip –為數(shù)據(jù)庫(kù)服務(wù)器的IP地址,如果是本地可寫:localhost或127.0.0.1。port –為數(shù)據(jù)庫(kù)的監(jiān)聽(tīng)端口,需要看安裝時(shí)的配置,缺省為1433。databasename –數(shù)據(jù)庫(kù)的名字。舉例如果要訪問(wèn)本地的數(shù)據(jù)庫(kù)allandb,端口1433,那么URL寫法如下:jdbc: microsoft: sqlserver:@localhost:1433; DatabaseName =allandb下載地址:http://www.microsoft.com/downloads/details.aspx
MySQL數(shù)據(jù)庫(kù)驅(qū)動(dòng)程序包名:mysql
-connector-java-3.1.11-bin.jar驅(qū)動(dòng)類的名字:com.mysql.jdbc.DriverJDBC URL:jdbc:mysql://dbip:port/databasename 說(shuō)明:驅(qū)動(dòng)程序包名有可能會(huì)變JDBC URL中黑色字體部分必須原封不動(dòng)的保留,為該驅(qū)動(dòng)識(shí)別的URL格式。紅色字體部需要根據(jù)數(shù)據(jù)庫(kù)的安裝情況填寫。其中各個(gè)部分含義如下:dbip –為數(shù)據(jù)庫(kù)服務(wù)器的IP地址,如果是本地可寫:localhost或127.0.0.1。port –為數(shù)據(jù)庫(kù)的監(jiān)聽(tīng)端口,需要看安裝時(shí)的配置,缺省為3306。databasename –數(shù)據(jù)庫(kù)的名字。舉例如果要訪問(wèn)本地的數(shù)據(jù)庫(kù)allandb,端口1433,那么URL寫法如下:jdbc:mysql://localhost:3306/allandb下載地址:http://dev.mysql.com/downloads/connector/j/
Access數(shù)據(jù)庫(kù)驅(qū)動(dòng)程序包名:該驅(qū)動(dòng)程序包含在JavaSE中,不需要額外安裝。驅(qū)動(dòng)類的名字:sun.jdbc.odbc.JdbcOdbcDriverJDBC URL:jdbc:odbc:datasourcename說(shuō)明:該驅(qū)動(dòng)只能工作在Windows系統(tǒng)中,首先需要在操作系統(tǒng)中建立一個(gè)可以訪問(wèn)Access數(shù)據(jù)庫(kù)的本地?cái)?shù)據(jù)源(ODBC),如果名字為allandb,那么URL寫法如下:jdbc:odbc:allandbPreparedStatement接口: 預(yù)編譯的sql語(yǔ)句對(duì)象 作用: 解決了書寫sql語(yǔ)句時(shí)一些特殊的字符與sql保留字符沖突的問(wèn)題,非常方便
/** *知識(shí)點(diǎn): *PreparedStatement接口及方法的使用 *程序目標(biāo): *java文件: *PreparedInsert.java:連接數(shù)據(jù)庫(kù),插入一條數(shù)據(jù) *JdbcUtil.java:實(shí)現(xiàn)一個(gè)工具類,功能:1.連接數(shù)據(jù)庫(kù) 2.關(guān)閉資源 */package moudule1.preparedstatement;import java.sql.*; import moudule1.com.*;public class PreparedInsert {public static void main(String[] args){String sql="insert into yuchen_user (id,name) values (?,?)";System.out.println(sql);Connection con=null;PreparedStatement ps=null;try{con=JdbcUtil.getConnection();ps=con.prepareStatement(sql);ps.setInt(1,2);ps.setString(2,"zhangsan");ps.executeUpdate();ps.setInt(1,3);ps.setString(2,"lisi");ps.executeUpdate();}catch(Exception e){e.printStackTrace();}finally{JdbcUtil.close(con,ps);}}}package moudule1.com;import java.sql.*;public class JdbcUtil{public static Connection getConnection() throws Exception{Class.forName("oracle.jdbc.driver.OracleDriver");return DriverManager.getConnection("jdbc:oracle:thin:@127.0.0.1:1521:name", "scott","tiger");}public static void close(Connection con,Statement st){close(con);close(st);}public static void close(Connection con,Statement st,ResultSet rs){close(con,st);close(rs);}public static void close(Connection con){try{con.close();}catch(Exception e){}}public static void close(Statement st){try{st.close();}catch(Exception e){}}public static void close(ResultSet rs){try{rs.close();}catch(Exception e){}}}數(shù)據(jù)庫(kù)的增刪改查的例子: /** *知識(shí)點(diǎn): *JDBC+SQL+ORACLE *程序目標(biāo): *UserDao.java:實(shí)現(xiàn)了數(shù)據(jù)庫(kù)的增刪改查 *JdbcUtil.java:工具類,有連庫(kù)和關(guān)閉資源的方法 */package moudule1.idus;import java.sql.*; import moudule1.com.*;public class UserDao{private String sql;private Connection con;private Statement st;private ResultSet rs;public UserDao(){sql=null;con=null;st=null;rs=null;}public void insert(){sql="insert into yuchen_user (id,name) values(";sql+="4,'zhouwu')";System.out.println(sql);try{con=JdbcUtil.getConnection();st=con.createStatement();st.executeUpdate(sql);}catch(Exception e){e.printStackTrace();}finally{JdbcUtil.close(con,st);}}public void delete(){sql="delete from yuchen_user where id=2";System.out.println(sql);try{con=JdbcUtil.getConnection();st=con.createStatement();st.executeUpdate(sql);}catch(Exception e){e.printStackTrace();}finally{JdbcUtil.close(con,st);}}public void update(){sql="update yuchen_user set name='liumang' where id=1";System.out.println(sql);try{con=JdbcUtil.getConnection();st=con.createStatement();st.executeUpdate(sql);}catch(Exception e){e.printStackTrace();}finally{JdbcUtil.close(con,st);}}public void select(){sql="select * from yuchen_user";System.out.println(sql);try{con=JdbcUtil.getConnection();st=con.createStatement();rs=st.executeQuery(sql);while(rs.next()){System.out.println(rs.getInt(1));System.out.println(rs.getString(2));}}catch(Exception e){e.printStackTrace();}finally{JdbcUtil.close(con,st,rs);}}public static void main(String[] args){UserDao ud=new UserDao();ud.select();ud.insert();ud.select();ud.update();ud.select();ud.delete();ud.select();}}一些常用的方法: /** *知識(shí)點(diǎn): *execute方法,getResultSet(),getUpdateCount() *程序目標(biāo): *JdbcUtil.java:工具類,連接數(shù)據(jù)庫(kù),關(guān)閉資源 *sqlExecutor.java:命令行參數(shù)輸入sql語(yǔ)句,并執(zhí)行該語(yǔ)句 */ package moudule1.fangfa;import java.sql.*; import moudule1.com.*;public class sqlExecutor{public static void main(String[] args){Connection con=null;Statement st=null;try{con=JdbcUtil.getConnection();st=con.createStatement();boolean str=st.execute(args[0]);if(str){ResultSet rs=st.getResultSet();while(rs.next()){System.out.println(rs.getInt("id")+":"+rs.getString("name"));}rs.close();}else{int row=st.getUpdateCount();System.out.println(row);}}catch(Exception e){e.printStackTrace();}finally{JdbcUtil.close(con,st);}}} 2. 補(bǔ)充JDBC連接MySQL加載及注冊(cè)JDBC驅(qū)動(dòng)程序 Class.forName("com.mysql.jdbc.Driver"); Class.forName("com.mysql.jdbc.Driver").newInstance(); JDBC URL 定義驅(qū)動(dòng)程序與數(shù)據(jù)源之間的連接 標(biāo)準(zhǔn)語(yǔ)法: <protocol(主要通訊協(xié)議)>:<subprotocol(次要通訊協(xié)議,即驅(qū)動(dòng)程序名稱)>:<data source identifier(數(shù)據(jù)源)> MySQL的JDBC URL格式: jdbc:mysql//[hostname][:port]/[dbname][?param1=value1][&param2=value2]…. 示例:jdbc:mysql://localhost:3306/sample_db?user=root&password=your_password 常見(jiàn)參數(shù): user 用戶名 password 密碼 autoReconnect 聯(lián)機(jī)失敗,是否重新聯(lián)機(jī)(true/false) maxReconnect 嘗試重新聯(lián)機(jī)次數(shù) initialTimeout 嘗試重新聯(lián)機(jī)間隔 maxRows 傳回最大行數(shù) useUnicode 是否使用Unicode字體編碼(true/false) characterEncoding 何種編碼(GB2312/UTF-8/…) relaxAutocommit 是否自動(dòng)提交(true/false) capitalizeTypeNames 數(shù)據(jù)定義的名稱以大寫表示 建立連接對(duì)象 String url="jdbc:mysql://localhost:3306/sample_db?user=root&password=your_password"; Connection con = DriverManager.getConnection(url); 建立SQL陳述式對(duì)象(Statement Object) Statement stmt = con.createStatement(); 執(zhí)行SQL語(yǔ)句 executeQuery() String query = "select * from test"; ResultSet rs=stmt.executeQuery(query); 結(jié)果集ResultSet while(rs.next()) {rs.getString(1);rs.getInt(2);} executeUpdate() String upd="insert into test (id,name) values(1001,xuzhaori)"; int con=stmt.executeUpdate(upd); execute() 示例: try{ } catch(SQLException sqle) { } finally { }Java類型和SQL類型 技術(shù)手冊(cè)P421 PreparedStatement(預(yù)編語(yǔ)句) PreparedStatement stmt = conn.prepareStatement("insert into test(id,name)values(?,?)"); stmt.setInt(1,id); stmt.setString(2,name); 注:一旦設(shè)定語(yǔ)句的參數(shù)值后,就可以多次執(zhí)行改語(yǔ)句,直到調(diào)用clearParameters()方法將他清除為止 CallableStatement(預(yù)儲(chǔ)程序)技術(shù)手冊(cè)P430 JDBC2.0使用 ResultSet對(duì)象中的光標(biāo)上下自由移動(dòng) Statement stmt = con.createStatement (ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_READ_ONLY); ResultSet rs=stmt.executeQuery("select * from test");public Statement createStatement(int resultSetType,int resultSetConcuttency) throws SQLExceptionresultSetType TYPE_FORWARD_ONLY 只能使用next()方法。 TYPE_SCROLL_SENSITIVE 可以上下移動(dòng),可以取得改變后的值。 TYPE_SCROLL_INSENSITIVE 可以上下移動(dòng)。 resultSetConcuttency CONCUR_READ_ONLY 只讀 CONCUR_UPDATABLE ResultSet對(duì)象可以執(zhí)行數(shù)據(jù)庫(kù)的新增、修改、和移除直接使用ResultSet對(duì)象執(zhí)行更新數(shù)據(jù) 新增數(shù)據(jù) Statement stmt=con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_PUDATABLE); ResultSet uprs=stmt.executeQuery("select * from test"); uprs.moveToInsertRow(); uprs.updateInt(1,1001); uprs.updateString(2,"許召日"); uprs.insertRow; 更新數(shù)據(jù) Statement stmt=con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_PUDATABLE); ResultSet uprs=stmt.executeQuery("select * from test"); uprs.last(); uprs.updateString("name","xuzhaori"); uprs.updateRow; 刪除數(shù)據(jù) Statement stmt=con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_PUDATABLE); ResultSet uprs=stmt.executeQuery("select * from test"); uprs.absolute(4); uprs.deleteRow();批處理 con.setAutoCommit(false); 關(guān)閉自動(dòng)認(rèn)可模式 Statement stmt=con.createStatement(); int[] rows; stmt.addBatch("insert into test values(1001,xuzhaori)"); stmt.addBatch("insert into test values(1002,xuyalin)"); rows=stmt.executeBatch(); con.commit(); 沒(méi)有任何錯(cuò)誤,執(zhí)行批處理stmt.executeBatch();JNDI-數(shù)據(jù)源(Data Source)與連接池(Connection Pool) Tomcat的JDBC數(shù)據(jù)源設(shè)置 技術(shù)手冊(cè)P439 連接池工具-Proxool Var 0.8.3 技術(shù)手冊(cè)P446 設(shè)置web.xml <?xml version="1.0" encoding="ISO-8859-1"?> <!--<?xml version="1.0" encoding="GB2312"?>--><web-app xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd" version="2.4"> …. <servlet> <servlet-name>ServletConfigurator</servlet-name> <servlet-class>org.logicalcobwebs.proxool.configuration.ServletConfigurator</servlet-class><init-param> <param-name>propertyFile</param-name> <param-value>WEB-INF/classes/Proxool.properties</param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet> 后端統(tǒng)計(jì)端口添加下列 <servlet> <servlet-name>Admin</servlet-name> <servlet-class>org.logicalcobwebs.proxool.admin.servlet.AdminServlet</servlet-class> </servlet><servlet-mapping> <servlet-name>Admin</servlet-name> <url-pattern>/Admin</url-pattern> </servlet-mapping>….</web-app>配置Proxool.properties jdbc-0.proxool.alias=JSPBook jdbc-0.proxool.driver-class=com.mysql.jdbc.Driver jdbc-0.proxool.driver-url=jdbc:mysql://localhost:3306/sample_db?user=root&password=browser&useUnicode=true&characterEncoding=UTF-8 jdbc-0.proxool.maximum-connection-count=10 jdbc-0.proxool.prototype-count=4 jdbc-0.proxool.house-keeping-test-sql=select CURRENT_DATE jdbc-0.proxool.verbose=true jdbc-0.proxool.statistics=10s,1m,1d 后端統(tǒng)計(jì)接口添加此行 jdbc-0.proxool.statistics-log-level=DEBUG 使用Proxool連接池 Connection con = DriverManager.getConnection("proxool.JSPBook"); Statement stmt = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE); String query = "SELECT * FROM employee"; ResultSet rs = stmt.executeQuery(query);

?

JDBC事務(wù)提交和回滾示例

以下是使用事務(wù)提交和回滾描述的例子?;趯?duì)環(huán)境和數(shù)據(jù)庫(kù)安裝在前面的章節(jié)中做此示例代碼已學(xué)習(xí)過(guò)。復(fù)制過(guò)去下面的例子中JDBCExample.java,編譯并運(yùn)行,如下所示://STEP 1. Import required packages import java.sql.*;public class JDBCExample {// JDBC driver name and database URLstatic final String JDBC_DRIVER = "com.mysql.jdbc.Driver"; static final String DB_URL = "jdbc:mysql://localhost/EMP";// Database credentialsstatic final String USER = "username";static final String PASS = "password";public static void main(String[] args) {Connection conn = null;Statement stmt = null;try{//STEP 2: Register JDBC driverClass.forName("com.mysql.jdbc.Driver");//STEP 3: Open a connectionSystem.out.println("Connecting to database...");conn = DriverManager.getConnection(DB_URL,USER,PASS);//STEP 4: Set auto commit as false.conn.setAutoCommit(false);//STEP 5: Execute a query to create statment with// required arguments for RS example.System.out.println("Creating statement...");stmt = conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_UPDATABLE);//STEP 6: INSERT a row into Employees tableSystem.out.println("Inserting one row....");String SQL = "INSERT INTO Employees " +"VALUES (106, 20, 'Rita', 'Tez')";stmt.executeUpdate(SQL); //STEP 7: INSERT one more row into Employees tableSQL = "INSERT INTO Employees " +"VALUES (107, 22, 'Sita', 'Singh')";stmt.executeUpdate(SQL);//STEP 8: Commit data here.System.out.println("Commiting data here....");conn.commit();//STEP 9: Now list all the available records.String sql = "SELECT id, first, last, age FROM Employees";ResultSet rs = stmt.executeQuery(sql);System.out.println("List result set for reference....");printRs(rs);//STEP 10: Clean-up environment rs.close();stmt.close();conn.close();}catch(SQLException se){//Handle errors for JDBC se.printStackTrace();// If there is an error then rollback the changes.System.out.println("Rolling back data here....");try{if(conn!=null)conn.rollback();}catch(SQLException se2){se2.printStackTrace();}//end try }catch(Exception e){//Handle errors for Class.forName e.printStackTrace();}finally{//finally block used to close resourcestry{if(stmt!=null)stmt.close();}catch(SQLException se2){}// nothing we can dotry{if(conn!=null)conn.close();}catch(SQLException se){se.printStackTrace();}//end finally try}//end trySystem.out.println("Goodbye!"); }//end mainpublic static void printRs(ResultSet rs) throws SQLException{//Ensure we start with first row rs.beforeFirst();while(rs.next()){//Retrieve by column nameint id = rs.getInt("id");int age = rs.getInt("age");String first = rs.getString("first");String last = rs.getString("last");//Display valuesSystem.out.print("ID: " + id);System.out.print(", Age: " + age);System.out.print(", First: " + first);System.out.println(", Last: " + last);}System.out.println();}//end printRs() }//end JDBCExample

現(xiàn)在讓我們來(lái)編譯上面的例子如下: C:\>javac JDBCExample.java C:\> 當(dāng)運(yùn)行JDBCExample,它會(huì)產(chǎn)生以下結(jié)果:C:\>java JDBCExample Connecting to database... Creating statement... Inserting one row.... Commiting data here.... List result set for reference.... ID: 100, Age: 18, First: Zara, Last: Ali ID: 101, Age: 25, First: Mahnaz, Last: Fatma ID: 102, Age: 30, First: Zaid, Last: Khan ID: 103, Age: 28, First: Sumit, Last: Mittal ID: 106, Age: 20, First: Rita, Last: Tez ID: 107, Age: 22, First: Sita, Last: Singh Goodbye! C:\>

?老師的例子:

JdbcDemo.java

package jdbc;import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.SQLException;public class JdbcDemo {/*** @param args*/public static void main(String[] args) {// TODO Auto-generated method stub String username = "test";String password = "123456";String url = "jdbc:oracle:thin:@localhost:1521:orcl";//localhost 127.0.0.1 orclConnection conn = null;try {Class.forName("oracle.jdbc.driver.OracleDriver"); //加載驅(qū)動(dòng)conn = DriverManager.getConnection(url,username,password); /* //String sql = "insert into demo(id,name,sex,address,birthday)
       values(2,'張三1','1','南京1',to_date('2014-12-12','yyyy-mm-dd'))";
int id = 3;String name = "李四";String sex = "1";String address = "北京";String birthday = "2012-12-12";String sql = "insert into demo(id,name,sex,address,birthday)
       values("+id+",'"+name+"','"+sex+"','"+address+"',
       to_date('"+birthday+"','yyyy-mm-dd'))";System.out.println(sql);Statement st = conn.createStatement();st.executeUpdate(sql);sql = "delete from demo where id="+id;
*//*String sql = "select id,name,sex,address,
to_char(birthday,'yyyy-mm-dd') birthday from demo";Statement st = conn.createStatement();ResultSet rs = st.executeQuery(sql);while(rs.next()){int id = rs.getInt("id");String name = rs.getString("name");String sex = rs.getString("sex");String address = rs.getString("address");String birthday = rs.getString("birthday");System.out.println(id);}rs.close();st.close();conn.close();
*/ /* int id = 4;String name = "李四";String sex = "1";String address = "北京";String birthday = "2012-12-12";String sql = "insert into demo(id,name,sex,address,birthday)
values(?,?,?,?,to_date('"+birthday+"','yyyy-mm-dd'))";PreparedStatement pst = conn.prepareStatement(sql);pst.setInt(1, id);pst.setString(2, name);pst.setString(3, sex);pst.setString(4, address);pst.executeUpdate();
*///1.手動(dòng)提交conn.setAutoCommit(false);int id = 6;String name = "李四";String sex = "1";String address = "北京";String birthday = "2012-12-12";String sql = "insert into demo(id,name,sex,address,birthday)
values(?,?,?,?,to_date('"+birthday+"','yyyy-mm-dd'))";PreparedStatement pst = conn.prepareStatement(sql);pst.setInt(1, id);pst.setString(2, name);pst.setString(3, sex);pst.setString(4, address);pst.executeUpdate();id = 7;sql = "insert into demo(id,name,sex,address,birthday)
values(?,?,?,?,to_date('"+birthday+"','yyyy-mm-dd'))";pst = conn.prepareStatement(sql);pst.setInt(1, id);pst.setString(2, name);pst.setString(3, sex);pst.setString(4, address);pst.executeUpdate();conn.commit();} catch (ClassNotFoundException e) {// TODO Auto-generated catch block e.printStackTrace();} catch(SQLException sqle){sqle.printStackTrace();try {conn.rollback(); //回滾} catch (SQLException e) {// TODO Auto-generated catch block e.printStackTrace();}}}}





































































































?

ConnDB.java

package jdbc;import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException;public class ConnDB {private String username = "test";private String password = "123456";private String url =
"jdbc:oracle:thin:@localhost:1521:orcl";private Connection conn;public Connection getConn() {try {Class.forName
(
"oracle.jdbc.driver.OracleDriver");conn =
DriverManager.getConnection
          (url,username,password);}
catch (ClassNotFoundException e) { e.printStackTrace();} catch(SQLException sqle){sqle.printStackTrace();}return conn;}}






















































































































































































?

DemoDao.java

package jdbc.dao;import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map;import jdbc.ConnDB; import jdbc.pojo.Demo;public class DemoDao {/*** 新增* @param demo*/public void add(Demo demo){ConnDB db = new ConnDB();Connection conn = db.getConn();String sql = "insert into demo(id,name,sex,address,birthday)
values(?,?,?,?,to_date('"+demo.getBirthday()+"','yyyy-mm-dd'))";try {PreparedStatement pst = conn.prepareStatement(sql);pst.setInt(1, demo.getId());pst.setString(2, demo.getName());pst.setString(3, demo.getSex());pst.setString(4, demo.getAddress());pst.executeUpdate();pst.close();conn.close();} catch (SQLException e) {// TODO Auto-generated catch block e.printStackTrace();}}public void update(Demo demo){ConnDB db = new ConnDB();Connection conn = db.getConn();String sql = "update demo set name=?,sex=?,address=?,birthday=
to_date('"+demo.getBirthday()+"','yyyy-mm-dd') where id=?";try {PreparedStatement pst = conn.prepareStatement(sql);pst.setString(1, demo.getName());pst.setString(2, demo.getSex());pst.setString(3, demo.getAddress());pst.setInt(4, demo.getId());pst.executeUpdate();pst.close();conn.close();} catch (SQLException e) {// TODO Auto-generated catch block e.printStackTrace();}} public void delete(int id){ConnDB db = new ConnDB();Connection conn = db.getConn();String sql = "delete from demo where id=?";try {PreparedStatement pst = conn.prepareStatement(sql); pst.setInt(1, id); pst.executeUpdate(); pst.close();conn.close();} catch (SQLException e) {// TODO Auto-generated catch block e.printStackTrace();}}public Demo getDemoById(int id){ConnDB db = new ConnDB();Connection conn = db.getConn();Demo demo = new Demo();String sql = "select id,name,sex,address,
to_char(birthday,'yyyy-mm-dd') birthday from demo where id=?";try {PreparedStatement pst = conn.prepareStatement(sql); pst.setInt(1, id);ResultSet rs = pst.executeQuery();if(rs.next()){demo.setId(rs.getInt("id"));demo.setName(rs.getString("name"));demo.setSex(rs.getString("sex"));demo.setAddress(rs.getString("address"));demo.setBirthday(rs.getString("birthday"));} pst.close();conn.close();} catch (SQLException e) {// TODO Auto-generated catch block e.printStackTrace();}return demo;}public Map getDemoMap(int id){Map hm = new HashMap();ConnDB db = new ConnDB();Connection conn = db.getConn();Demo demo = new Demo();String sql = "select id,name,sex,address,
to_char(birthday,'yyyy-mm-dd') birthday from demo where id=?";try {PreparedStatement pst = conn.prepareStatement(sql); pst.setInt(1, id);ResultSet rs = pst.executeQuery();if(rs.next()){hm.put("id",rs.getInt("id"));hm.put("name",rs.getString("name"));hm.put("sex",rs.getString("sex"));hm.put("address",rs.getString("address"));hm.put("birthday",rs.getString("birthday"));} pst.close();conn.close();} catch (SQLException e) {// TODO Auto-generated catch block e.printStackTrace();}return hm;}public List getAllDemo(){List list = new ArrayList();ConnDB db = new ConnDB();Connection conn = db.getConn();Demo demo;String sql = "select id,name,sex,address,
to_char(birthday,'yyyy-mm-dd') birthday from demo";try {PreparedStatement pst = conn.prepareStatement(sql); ResultSet rs = pst.executeQuery();while(rs.next()){demo = new Demo();demo.setId(rs.getInt("id"));demo.setName(rs.getString("name"));demo.setSex(rs.getString("sex"));demo.setAddress(rs.getString("address"));demo.setBirthday(rs.getString("birthday"));list.add(demo);} pst.close();conn.close();} catch (SQLException e) {// TODO Auto-generated catch block e.printStackTrace();}return list;}public static void main(String[] args){Demo demo = new Demo();/*demo.setId(8);demo.setName("張炸1");demo.setSex("0");demo.setAddress("上海1");demo.setBirthday("2012-2-2");*/DemoDao dd = new DemoDao();Map hm = dd.getDemoMap(2);System.out.println(hm.get("name"));List list = dd.getAllDemo();Iterator itr = list.iterator();while(itr.hasNext()){demo = (Demo)itr.next();//System.out.println(demo.getName()); }}}

?

Demo.java

package jdbc.pojo;public class Demo {private int id;private String name;private String sex;private String address;private String birthday;public int getId() {return id;}public void setId(int id) {this.id = id;}public String getName() {return name;}public void setName(String name) {this.name = name;}public String getSex() {return sex;}public void setSex(String sex) {this.sex = sex;}public String getAddress() {return address;}public void setAddress(String address) {this.address = address;}public String getBirthday() {return birthday;}public void setBirthday(String birthday) {this.birthday = birthday;}}




































































































































































?

?

posted on 2014-12-19 10:41 1iqueen 閱讀(...) 評(píng)論(...) 編輯 收藏

轉(zhuǎn)載于:https://www.cnblogs.com/lkboy/p/4173375.html

總結(jié)

以上是生活随笔為你收集整理的[Java]jdbc[转]的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。

如果覺(jué)得生活随笔網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔推薦給好友。