??xml version="1.0" encoding="utf-8" standalone="yes"?>
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.List;
import com.semovy.bean.Database;
public class SQLServerDatabase implements Database {
private String driver = null;
private String pwd = null;
private String user = null;
private String url = null;
private Connection connection = null;
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getUser() {
return user;
}
public void setUser(String user) {
this.user = user;
}
public String getDriver() {
return driver;
}
public String getPwd() {
return pwd;
}
public void setDriver(String driver)
{
this.driver = driver;
}
public void setPwd(String pwd)
{
this.pwd = pwd;
}
public Connection getConnection()
{
openConnection();
return this.connection;
}
public void setConnection(Connection connection) {
this.connection = connection;
}
public List getData() {
return null;
}
public SQLServerDatabase(String driver,String url,String user,String pwd)
{
this.driver = driver;
this.url = url;
this.user = user;
this.pwd = pwd;
try
{
System.out.println("start");
Class.forName(this.getDriver()).newInstance();
this.connection = DriverManager.getConnection(this.getUrl(), this.getUser(), this.getPwd());
System.out.println("OK");
}catch(SQLException e)
{
System.out.println(e.getLocalizedMessage());
}
catch(ClassNotFoundException e)
{
System.out.println(e.getLocalizedMessage());
}
catch(Exception e)
{
System.out.println(e.getLocalizedMessage());
}
}
/**
*
* @return
*/
private Connection openConnection()
{
if(this.connection != null)
{
return this.connection;
}
else
{
try
{
Class.forName(this.getDriver()).newInstance();
this.connection = DriverManager.getConnection(this.getUrl(), this.getUser(), this.getPwd());
}catch(SQLException e)
{
System.out.println(e.getLocalizedMessage());
}
catch(ClassNotFoundException e)
{
System.out.println(e.getLocalizedMessage());
}
catch(Exception e)
{
System.out.println(e.getLocalizedMessage());
}
return this.connection;
}
}
public void closeConnection()
{
try
{
if(this.getConnection() != null && !this.connection.isClosed())
{
this.connection.close();
}
}catch(SQLException e)
{
System.out.println(e.getLocalizedMessage());
}
}
public ResultSet executeQuery(String sqlExp)
{
ResultSet rs = null;
Statement stmt = null;
try
{
stmt = this.getConnection().createStatement();
rs = stmt.executeQuery(sqlExp);
}catch(SQLException e)
{
System.out.println(e.getLocalizedMessage());
}
return rs;
}
public void executeUpdate(String sqlExp)
{
try
{
this.getConnection().createStatement().executeUpdate(sqlExp);
}catch(SQLException e)
{
System.out.println(e.getLocalizedMessage());
}
}
public void executeBatchUpdate()
{
try
{
long start = System.currentTimeMillis();
Statement stmt = this.getConnection().createStatement();
for(int i=0;i < 10000;i++)
{
stmt.addBatch("insert into item values(2,'item" + i + "')");
if(i%500 == 0 && i>0)
stmt.executeBatch();
}
stmt.executeBatch();
this.getConnection().commit();
stmt.close();
stmt = null;
long spendTime = System.currentTimeMillis() - start;
System.out.println("向数据库插入一万条记录用去:" + spendTime*1.0/1000 + " s");
}catch(SQLException e)
{
System.out.println(e.getLocalizedMessage());
}
}
public void display(ResultSet rs)
{
try
{
ResultSetMetaData rsmd = rs.getMetaData();
int colLen = rsmd.getColumnCount();
while(rs.next())
{
for(int i=0; i<colLen;i++)
{
System.out.print(rsmd.getColumnName(i+1) + ": " + rs.getObject(i+1) + " ");
}
System.out.println();
}
}catch(SQLException e)
{
System.out.println(e.getLocalizedMessage());
}
}
}
package com.semovy.test;
import com.semovy.service.impl.SQLServerDatabase;
public class TestHelloWorld {
public static void main(String[] args) {
// ApplicationContext appContext = new
// FileSystemXmlApplicationContext("classpath:config.xml");
// Hello hello = (Hello)appContext.getBean("hello");
// hello.saySaluation();
// IoC Inversion of Control 反向控制.
// 发明者新命名?DI dipendency Injection 依赖注入.
// 反向控制是实C赖抽?不是抽象依赖实现.
SQLServerDatabase sqlServerDB = new SQLServerDatabase(
"com.microsoft.jdbc.sqlserver.SQLServerDriver", "jdbc:microsoft:sqlserver://localhost:1433;DatabaseName=test",
"sa", "1234");
sqlServerDB.executeUpdate("drop table item if exist create table item(id int not null identity(1,1) primary key,int categoryId not null,itemName varchar(255) default '')");
sqlServerDB.executeUpdate("delete from item");
sqlServerDB.executeBatchUpdate();
sqlServerDB.display(sqlServerDB.executeQuery("select top 100 * from item"));
sqlServerDB.closeConnection();
}
}
Class.forName("oracle.jdbc.driver.OracleDriver").newInstance();
String url="jdbc:oracle:thin:@localhost:1521:orcl"; //orcl为数据库的SID
String user="test";
String password="test";
Connection conn= DriverManager.getConnection(url,user,password);
Class.forName("com.ibm.db2.jdbc.app.DB2Driver ").newInstance();
String url="jdbc:db2://localhost:5000/sample"; //sampleZ的数据库?
String user="admin";
String password="";
Connection conn= DriverManager.getConnection(url,user,password);
Class.forName("com.microsoft.jdbc.sqlserver.SQLServerDriver").newInstance();
String url="jdbc:microsoft:sqlserver://localhost:1433;DatabaseName=mydb";
//mydb为数据库
String user="sa";
String password="";
Connection conn= DriverManager.getConnection(url,user,password);
Class.forName("com.sybase.jdbc.SybDriver").newInstance();
String url =" jdbc:sybase:Tds:localhost:5007/myDB";//myDBZ的数据库?
Properties sysProps = System.getProperties();
SysProps.put("user","userid");
SysProps.put("password","user_password");
Connection conn= DriverManager.getConnection(url, SysProps);
5、Informix数据?/strong>
Class.forName("com.informix.jdbc.IfxDriver").newInstance();
String url = "jdbc:informix-sqli://123.45.67.89:1533/myDB:INFORMIXSERVER=myserver;
user=testuser;password=testpassword"; //myDB为数据库?
Connection conn= DriverManager.getConnection(url);
6、MySQL数据?/strong>
Class.forName("org.gjt.mm.mysql.Driver").newInstance();
String url ="jdbc:mysql://localhost/myDB?user=soft&password=soft1234&useUnicode=true&characterEncoding=8859_1"
//myDB为数据库?
Connection conn= DriverManager.getConnection(url);
7、PostgreSQL数据?/strong>
Class.forName("org.postgresql.Driver").newInstance();
String url ="jdbc:postgresql://localhost/myDB" //myDB为数据库?
String user="myuser";
String password="mypassword";
Connection conn= DriverManager.getConnection(url,user,password);
8、access数据库直q用ODBC?br />
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver") ;
String url="jdbc:odbc:Driver={MicroSoft Access Driver (*.mdb)};DBQ="+application.getRealPath("/Data/ReportDemo.mdb");
Connection conn = DriverManager.getConnection(url,"","");
Statement stmtNew=conn.createStatement() ;
二、JDBCq接MySql方式
下面是用JDBCq接MySql的一个小的教E?
1、查N动程?/strong>
MySQL目前提供的java驱动E序为Connection/JQ可以从MySQL官方|站下蝲Qƈ扑ֈmysql-connector-java-3.0.15-ga-bin.jar文gQ此驱动E序为纯java驱动E序Q不需做其他配|?br />
2、动态指定classpath
如果需要执行时动态指定classpathQ就在执行时采用Qcp方式。否则将上面?jar文g加入到classpath环境变量中?br />
3、加载驱动程?/strong>
try{
Class.forName(com.mysql.jdbc.Driver);
System.out.println(Success loading Mysql Driver!);
}catch(Exception e)
{
System.out.println(Error loading Mysql Driver!);
e.printStackTrace();
}
4、设|连接的url
jdbcQmysqlQ?/localhost/databasename[?pa=va][Qpa=va]
三、以下列Z在用JDBC来连接Oracle数据库时可以使用的一些技?/strong>
1、在客户端Y件开发中使用Thin驱动E序
在开发Java软g斚wQOracle的数据库提供了四U类型的驱动E序Q二U用于应用Y件、applets、servlets{客L(fng)软gQ另外二U用于数据库中的Java存储q程{服务器端Y件。在客户机端软g的开发中Q我们可以选择OCI驱动E序或Thin驱动E序。OCI驱动E序利用Java本地化接口(JNIQ,通过Oracle客户端Y件与数据库进行通讯。Thin驱动E序是纯Java驱动E序Q它直接与数据库q行通讯。ؓ(f)了获得最高的性能QOracle在客L(fng)软g的开发中使用OCI驱动E序Q这g是正的。但我徏议用Thin驱动E序Q因为通过多次试发现Q在通常情况下,Thin驱动E序的性能都超q了OCI驱动E序?br />
2、关闭自动提交功能,提高pȝ性能
在第一ơ徏立与数据库的q接Ӟ在缺省情况下Q连接是在自动提交模式下的。ؓ(f)了获得更好的性能Q可以通过调用带布?yu)(dng)值false参数的ConnectioncȝsetAutoCommit()Ҏ(gu)关闭自动提交功能Q如下所C:(x)
conn.setAutoCommit(false);
值得注意的是Q一旦关闭了自动提交功能Q我们就需要通过调用Connectioncȝcommit()和rollback()Ҏ(gu)来h工的方式对事务进行管理?br />
3、在动态SQL或有旉限制的命令中使用Statement对象
在执行SQL命o(h)Ӟ我们有二U选择Q可以用PreparedStatement对象Q也可以使用Statement对象。无论多次C用同一个SQL命o(h)QPreparedStatement都只对它解析和编译一ơ。当使用Statement对象Ӟ每次执行一个SQL命o(h)Ӟ都会(x)对它q行解析和编译。这可能?x)你认为,使用PreparedStatement对象比用Statement对象的速度更快。然而,我进行的试表明Q在客户端Y件中Q情况ƈ非如此。因此,在有旉限制的SQL操作中,除非成批地处理SQL命o(h)Q我们应当考虑使用Statement对象?br />
此外Q用Statement对象也得编写动态SQL命o(h)更加单,因ؓ(f)我们可以字W串q接在一P建立一个有效的SQL命o(h)。因此,我认为,Statement对象可以使动态SQL命o(h)的创建和执行变得更加单?br />
4、利用helper函数对动态SQL命o(h)q行格式?/strong>
在创Z用Statement对象执行的动态SQL命o(h)Ӟ我们需要处理一些格式化斚w的问题。例如,如果我们惛_Z个将名字O'Reilly插入表中的SQL命o(h)Q则必须使用二个相连的?'”号替换O'Reilly中的?”号。完成这些工作的最好的Ҏ(gu)是创Z个完成替换操作的helperҎ(gu)Q然后在q接字符串心服用公式表达一个SQL命o(h)Ӟ使用创徏的helperҎ(gu)。与此类似的是,我们可以让helperҎ(gu)接受一个Date型的|然后让它输出ZOracle的to_date()函数的字W串表达式?br />
5、利用PreparedStatement对象提高数据库的M效率
在用PreparedStatement对象执行SQL命o(h)Ӟ命o(h)被数据库q行解析和编译,然后被放到命令缓冲区。然后,每当执行同一个PreparedStatement对象Ӟ它就?x)被再解析一ơ,但不?x)被再次~译。在~冲Z可以发现预编译的命o(h)Qƈ且可以重C用。在有大量用L(fng)企业U应用Y件中Q经怼(x)重复执行相同的SQL命o(h)Q用PreparedStatement对象带来的编译次数的减少能够提高数据库的M性能。如果不是在客户端创建、预备、执行PreparedStatementd需要的旉长于StatementdQ我?x)徏议在除动态SQL命o(h)之外的所有情况下使用PreparedStatement对象?br />
6、在成批处理重复的插入或更新操作中用PreparedStatement对象
如果成批地处理插入和更新操作Q就能够显著地减它们所需要的旉。Oracle提供的Statement?CallableStatementq不真正地支持批处理Q只有PreparedStatement对象才真正地支持批处理。我们可以用addBatch()和executeBatch()Ҏ(gu)选择标准的JDBC批处理,或者通过利用PreparedStatement对象的setExecuteBatch()Ҏ(gu)和标准的executeUpdate()Ҏ(gu)选择速度更快的Oracle专有的方法。要使用Oracle专有的批处理机制Q可以以如下所C的方式调用setExecuteBatch()Q?br />
PreparedStatement pstmt3D null;
try {
((OraclePreparedStatement)pstmt).setExecuteBatch(30);
...
pstmt.executeUpdate();
}
调用setExecuteBatch()时指定的值是一个上限,当达到该值时Q就?x)自动地引发SQL命o(h)执行Q标准的executeUpdate()Ҏ(gu)׃(x)被作为批处理送到数据库中。我们可以通过调用PreparedStatementcȝsendBatch()Ҏ(gu)随时传输批处理Q务?br />
7、用Oracle locatorҎ(gu)插入、更新大对象QLOBQ?br />
Oracle的PreparedStatementcM完全支持BLOB和CLOB{大对象的处理,其是Thin驱动E序不支持利用PreparedStatement对象的setObject()和setBinaryStream()Ҏ(gu)讄BLOB的|也不支持利用setCharacterStream()Ҏ(gu)讄CLOB的倹{只有locator本n中的Ҏ(gu)才能够从数据库中获取LOBcd的倹{可以用PreparedStatement对象插入或更新LOBQ但需要用locator才能获取LOB的倹{由于存在这二个问题Q因此,我徏议用locator的方法来插入、更新或获取LOB的倹{?br />
8、用SQL92语法调用存储q程
在调用存储过E时Q我们可以用SQL92或Oracle PL/SQLQ由于用Oracle PL/SQLq没有什么实际的好处Q而且?x)给以后l护你的应用E序的开发h员带来麻烦,因此Q我在调用存储过E时使用SQL92?br />
9、用Object SQL对象模式{Ud数据库中
既然可以Oracle的数据库作ؓ(f)一U面向对象的数据库来使用Q就可以考虑应用程序中的面向对象模式{到数据库中。目前的Ҏ(gu)是创建Java bean作ؓ(f)伪装的数据库对象Q将它们的属性映到关系表中Q然后在q些bean中添加方法。尽这样作在Java中没有什么问题,但由于操作都是在数据库之外进行的Q因此其他访问数据库的应用Y件无法利用对象模式。如果利用Oracle的面向对象的技术,可以通过创徏一个新的数据库对象cd在数据库中模仿其数据和操作,然后使用JPublisher{工L(fng)成自qJava beancR如果用这U方式,不但Java应用E序可以使用应用软g的对象模式,其他需要共享你的应用中的数据和操作的应用Y件也可以使用应用软g中的对象模式?br />
10、利用SQL完成数据库内的操?/strong>
我要向大家介l的最重要的经验是充分利用SQL的面向集合的Ҏ(gu)来解x据库处理需求,而不是用Java{过E化的编E语a?br />
如果~程人员要在一个表中查找许多行Q结果中的每个行都会(x)查找其他表中的数据,最后,~程人员创徏了独立的UPDATE命o(h)来成批地更新W一个表中的数据。与此类似的d可以通过在set子句中用多列子查询而在一个UPDATE命o(h)中完成。当能够在单一的SQL命o(h)中完成Q务,何必要让数据在网上流来流ȝQ我用户认真学习(fn)如何最大限度地发挥SQL的功能?