日期:2014-05-16 浏览次数:20538 次
附件:完整的JDBC程序范例(连接Oracle)
import java.sql.*;
public class TestJDBC {
public static void main(String[] args) {
ResultSet rs = null;
Statement stmt = null;
Connection conn = null;
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
//new oracle.jdbc.driver.OracleDriver();
conn = DriverManager.getConnection("jdbc:oracle:thin:@127.0.0.1:1521:mydb", "scott", "tiger");
stmt = conn.createStatement();
rs = stmt.executeQuery("select * from dept");
while(rs.next()) {
System.out.println(rs.getString("deptno"));
System.out.println(rs.getInt("deptno"));
}
} catch (ClassNotFoundException e) {
e.printStackTrace(); //此处应用logforJ替换
} catch (SQLException e) {
e.printStackTrace(); //此处应用logforJ替换
} finally {
try {
if(rs != null) {
rs.close();
rs = null;
}
if(stmt != null) {
stmt.close();
stmt = null;
}
if(conn != null) {
conn.close();
conn = null;
}
} catch (SQLException e) {
e.printStackTrace(); //此处应用logforJ替换
}
}
}
}
Lomboz_eclipse
1.Eclipse的J2EE插件版:
①Eclipse基于插件实现扩展,Lomboz要依赖于其他Eclipse插件
②竞争对手为:MyEclipse、JBuilder
③下载:搜索lomboz Eclipse选择all in one Eclipse r3.2
JDBC (数据库的链接纽带)
1.基于数据库的API进行编程的时候:变换数据库就要改变程序的代码为相应的API
进行分层设计:使用ODBC/JDBC,屏蔽数据库具体API,可以方便的变换数据库
JDBC的缺陷:SQL语句在不同种类数据库之间的区别没有屏蔽掉
2.在java端使用统一接口,在不同的数据库端用不同的数据库接口
3.编程步骤:import java.sql.*;
Oracle提供的JDBC的jar包:oracle\ora90\jdbc\lib\classes12.jar
工程文件夹右键|Build path|add external archive将该jar包添加到工程中
①Load the Driver:Class.forName(“Oracle.jdbc.driver.OracleDriver”)
DriverManager作为连接数据库的大管家,实例化时自动向其注册(不用显示调用其registerDriver方法)
//new Oracle.jdbc.driver.OracleDriver
②Connect to the DataBase:定义标准Interface Connection
Connection conn = DriverManager.getConnection(“jdbc:oracle:thin:@ip地址:端口号1521:SID的名字”,”scott”,”tiger”)
③Execute the SQL:
Statement stmt = conn.CreateStatement();
ResultSet rs = stmt.executeQuery(“select * from dept”