新聞中心
假定 Joe 是一名 QA,他需要為功能測試在 SAMPLE 數(shù)據(jù)庫中創(chuàng)建新的雇員。在 Jython 中,Joe 進(jìn)行少量工作就可以編寫他自己的腳本,進(jìn)行Jython數(shù)據(jù)庫插入。

成都創(chuàng)新互聯(lián)是一家專注于成都做網(wǎng)站、成都網(wǎng)站設(shè)計與策劃設(shè)計,坡頭網(wǎng)站建設(shè)哪家好?成都創(chuàng)新互聯(lián)做網(wǎng)站,專注于網(wǎng)站建設(shè)十年,網(wǎng)設(shè)計領(lǐng)域的專業(yè)建站公司;建站業(yè)務(wù)涵蓋:坡頭等地區(qū)。坡頭做網(wǎng)站價格咨詢:13518219792
例如,Joe 可以在 SAMPLE 數(shù)據(jù)庫中通過運(yùn)行“jython batchinsert.jy joescript.txt”,創(chuàng)建三名新雇員。
清單 6. joescript.txt
- createEmployee(firstName='JOHN',midinit='M',lastName='DOE',salary=32888.55,sex='M',workdept='A01',
- job='DESIGNER')
- createEmployee(firstName='MANAGER',midinit='M',lastName='DOE',salary=50000,sex='M',workdept='A01',
- job='MANAGER')
- createEmployee(firstName='SARA',midinit='M',lastName='DOE',salary=40000,sex='F',workdept='C01',
- job='DESIGNER')
如果 Joe 想要添加另一名 Employee,就只需用他喜歡的文本編輯器編輯“joescript.txt”。
Jython數(shù)據(jù)庫插入的腳本背后的功能十分簡單。Jython 有一個名為 execfile(filename) 的內(nèi)置函數(shù)。如果我們將 createEmployee() 實現(xiàn)為 Jython 函數(shù),用于向 EMPLOYEE 表插入一行記錄,那么 execfile('joescript.txt') 將按照 Joe 需要的數(shù)目插入雇員。
換言之,我們利用 Jython 的解釋器,并可以為 Joe 派生一個像這樣的小的測試語言。該解決方案也是可擴(kuò)展的。如果 Joe 需要在腳本中刪除或更新雇員,就只需要添加另一函數(shù)。對于 Joe 來說,最酷的事情就是學(xué)習(xí)曲線很短。他可以立刻編寫這樣的腳本,而沒有意識到正在進(jìn)行 Jython 函數(shù)調(diào)用。
清單 7. (batchinsert.jy)createEmployee 函數(shù)
- from java.lang import *
- from java.sql import *
- import sys
- def createEmployee(**args):
- global stmt
- sqlTemplate=
- "INSERT into EMPLOYEE (EMPNO,FIRSTNAME,MIDINIT,LASTNAME,SALARY,SEX,EDLEVEL, HIREDATE, WORKDEPT,JOB)
- values ((select RTRIM(CHAR(MAX(INT(EMPNO))+1)) from EMPLOYEE),
- '%(firstName)s', '%(midinit)s','%(lastName)s',
- %(salary).2f,'%(sex)s' ,18, CURRENT DATE,'%(workdept)s','%(job)s')"
- # dictionary based SQL string formatting
- sql=sqlTemplate % args
- stmt.addBatch(sql)
- # load DB2 JDBC type 2 driver
- Class.forName("COM.ibm.db2.jdbc.app.DB2Driver").newInstance()
- con = DriverManager.getConnection( 'jdbc:db2:sample', 'vyang','jythonrocks');
- con.setAutoCommit(0)
- stmt = con.createStatement()
- execfile(sys.argv[1])
- stmt.executeBatch()
- stmt.close()
- # commit
- con.commit()
- con.close()
Jython數(shù)據(jù)庫插入的這部分有許多新內(nèi)容。
con.setAutoCommit(0) 用于關(guān)閉自動提交(auto commit),就像 JDBC 調(diào)用中的 con.setAutoCommit(false) 一樣。
用于成批插入的 stmt.addBatch(sql) 、 stmt.executeBatch() 能有效地加快批量插入的速度。該技術(shù)還在 Neo 的加載仿真器中用于進(jìn)行大容量的插入。
global stmt 將使 stmt 成為一個共享的全局變量,很適用于該環(huán)境中。
def createEmployee(**args) 接收參數(shù)為字典 args ,并顯示 Jython 函數(shù)聲明是多么靈活。
sql=sqlTemplate % args 使用基于字典的 SQL 字符串格式化,我們在 select2.jy 中已經(jīng)了解。
【編輯推薦】
- Jython開發(fā)的JUnit測試包
- 創(chuàng)建Jython類的過程探討
- 輕松創(chuàng)建Jython全局函數(shù)
- 直接在源文件中編寫Jython代碼
- Jython入門指導(dǎo):語言特性簡介
當(dāng)前標(biāo)題:如何進(jìn)行Jython數(shù)據(jù)庫插入(JDBC)
轉(zhuǎn)載注明:http://m.5511xx.com/article/cogiijo.html


咨詢
建站咨詢
