Java JDBC 连接Oracle

16 篇文章 0 订阅
12 篇文章 0 订阅

                         我使用的连接方式是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);
		}
	}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值