下面的代码片段可以和MySQL数据库建立连接,并读取数据。类似的,可以很方便的连接DB2,Oracle,等,前提是把他们的Driver和classpath关联起来。
如果是DB2,则把driver改成 com.ibm.db2.jcc.DB2Driver,相应的驱动可以从安装DB2的文件夹SQLLIB\java中找到,db2jcc.jar,放在classpath路径下。 相应的,把url改成 “jdbc:dbc://serverip:port/databasename即可。
import java.sql.*;
public class Select {
public static void main(String args[]) {
String url = "jdbc:msql://carthage.imaginary.com/ora";
Connection con = null;
try {
String driver = "com.imaginary.sql.msql.MsqlDriver";
Class.forName(driver).newInstance( );
}
catch( Exception e ) {
System.out.println("Failed to load mSQL driver.");
return;
}
try {
con = DriverManager.getConnection(url, "username", "password");
Statement select = con.createStatement( );
ResultSet result = select.executeQuery
("SELECT test_id, test_val FROM test");
System.out.println("Got results:");
while(result.next( )) { // process results one row at a time
int key;
String val;
key = result.getInt(1);
if( result.wasNull( ) ) {
key = -1;
}
val = result.getString(2);
if( result.wasNull( ) ) {
val = null;
}
System.out.println("key = " + key);
System.out.println("val = " + val);
}
}
catch( Exception e ) {
e.printStackTrace( );
}
finally {
if( con != null ) {
try { con.close( ); }
catch( Exception e ) { e.printStackTrace( ); }
}
}
}
}