我使用的连接方式是jdbc:oracle:thin:@<host>:<port>:<SID>
其中,<host>指的是 本机地址,<port>指的是端口号,<SID> 指的是oracle实例名称比如orcl
注意:还需要将jdbc14.jar这个jar文件导入到你的java工程里面去。具体方法是,右键工程名,选择Build Path-->Configure Build Path-->add External JARs.导入就ok啦!
废话不多说,贴代码!
import java.sql.*;
import java.util.logging.Level;
import java.util.logging.Logger;
public class Test {
public static void main(String[] argv) {
try {
try {
// 注册JDBC驱动
Class.forName("oracle.jdbc.driver.OracleDriver");
} catch (ClassNotFoundException ex) {
Logger.getLogger(Test.class.getName()).log(Level.SEVERE, null,
ex);
}
// 创建数据库连接
String url = "jdbc:oracle:thin:@127.0.0.1:1521:ORCL";
String username = "scott";
String password = "tiger";
Connection conn = null;
try {
conn = DriverManager.getConnection(url, username, password);
} catch (SQLException ex) {
Logger.getLogger(Test.class.getName()).log(Level.SEVERE, null,
ex);
}
Statement statement = null;
try {
statement = conn.createStatement();
} catch (SQLException ex) {
Logger.getLogger(Test.class.getName()).log(Level.SEVERE, null,
ex);
}
ResultSet result;
// 创建表
System.out.println("--Creating Tables--");
statement.executeUpdate("CREATE TABLE Person(name VARCHAR2(100) PRIMARY KEY,age INTEGER,live_in VARCHAR2(100) )");
// 插入记录
System.out.println("--Inserting Data--");
statement.executeUpdate("INSERT INTO Person (name, age, live_in) VALUES('Robert Bellamy',24,'England')");
statement.executeUpdate("INSERT INTO Person (name, age, live_in) VALUES ('Grayham Downer',null,'Africa')");
statement.executeUpdate("INSERT INTO Person (name, age, live_in) VALUES ('Timothy French',24,'Africa')");
statement.executeUpdate("INSERT INTO Person (name, age, live_in) VALUES ('Butch Fad',53,'USA')");
statement.executeUpdate("INSERT INTO Person (name, age, live_in) VALUES ('Judith Brown',34,'Africa')");
// 查询
System.out.println("--SQL queries--");
result = statement.executeQuery("SELECT AVG(age) FROM Person");
if (result.next()) {
System.out.println("AV.age: " + result.getDouble(1));
}
System.out.println();
result = statement
.executeQuery("SELECT name FROM Person WHERE live_in = 'Africa'");
System.out.println("All people that live in Africa:");
while (result.next()) {
System.out.println(" " + result.getString(1));
}
// 删除表
statement.execute("DROP TABLE Person");
statement.close();
conn.close();
} catch (SQLException ex) {
Logger.getLogger(Test.class.getName()).log(Level.SEVERE, null, ex);
}
}
}