欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

JDBC连接Oracle数据库示例代码(含ojdbc驱动包)

程序员文章站 2024-03-13 17:35:51
...

一、mysql说明

JDBC连接Oracle数据库,JDBC连接Mysql点击这里,需要依赖ojdbc驱动包。

否则报异常如下JDBC连接Oracle数据库示例代码(含ojdbc驱动包)

 

二、连接介质

Oracle驱动架包ojdbc14-10.2.0.4.0.jar

https://pan.baidu.com/s/1GdaoJPfrV8L8oV2dy4aaMg

 

三、连接示例

3.1 创建库表(TEST.USER)

CREATE DATABASE test DEFAULT CHARACTER SET utf8 COLLATE utf8_general_ci;
-- DROP TABLE IF EXISTS test.user;
create table test.user(
	id number(7) primary key not null,
	name varchar2(255),
	sex char(1),
	age number(3)
);
insert into TEST.user(id,name,sex,age) values('1','张一','男',21);
insert into TEST.user(id,name,sex,age) values('2','张二','女',22);
insert into TEST.user(id,name,sex,age) values('3','张三','男',23);

 

3.2 示例代码

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
public class JdbcOracleTest {
	//定义JDBC驱动driverClassName驱动名称
	//oracle驱动名
	private final static String DRIVER_CLASS_NAME = "oracle.jdbc.driver.OracleDriver";
	public static void main(String[] args) throws ClassNotFoundException, SQLException {
		//1.加载JDBC驱动
		Class.forName(DRIVER_CLASS_NAME);
		//2.获取数据库的连接(Connection)对象
		Connection connection = DriverManager.getConnection(
				"jdbc:oracle:thin:@127.0.0.1:1521:orcl",	//oracle连接url
				"root", //数据库用户名
				"rootpassword"); //密码
		//3.获取数据库的操作(PrepareStatement)对象
		PreparedStatement prepareStatement = connection.prepareStatement("select * from TEST.user where id = ?");
		//4.设置传入参数
		prepareStatement.setInt(1, 1);
		//5.上传sql语句到服务器执行(excute),并返回结果集(ResultSet)
		ResultSet result = prepareStatement.executeQuery();
		//6.处理返回的ResultSet结果集
		while (result.next()) {
			System.out.print(result.getInt("id")+",");
			System.out.print(result.getString("name")+",");
			System.out.print(result.getString("sex")+",");
			System.out.print(result.getInt("age"));
			System.out.print("\n");
		}
		//7.释放相关资源:Connection对象、PrepareStatement对象、ResultSet对象。
		connection.close();
		prepareStatement.close();
		result.close();
	}
}

 

相关标签: jdbc连接数据库