ecplise连接数据库
1.导入jar包
针对于11g的oracle版本,在以下目录中找到对应的jar并导入到项目运行环境中
app\oracle\product\11.2.0\dbhome_1\jdbc\lib下的ojdbc6.jar
app\oracle\product\11.2.0\client_1\oui\jlib\classes12.jar
2.新建一个 jdbc类进行如下操作
package com_it_JDBC; import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; import java.sql.Statement; import java.util.concurrent.CountDownLatch; public class JdbcDemo { public static void main(String[] args) { //定义oracle数据库驱动的类 String driverclass = "oracle.jdbc.OracleDriver"; //定义连接oracle的Url String url = "jdbc:oracle:thin:@192.168.0.1:1521/orcl" ; //登入用户名 String username = "admin" ; //密码 String password = "root" ; Connection conn = null; Statement stmt = null; ResultSet rs = null; String querysql = "select * from person "; try { //注册数据库的驱动程序,将类加载到内存中 Class.forName(driverclass); //获得数据库连接 conn = DriverManager.getConnection(url, username, password); //创建sql执行对象 stmt=conn.createStatement(); //执行sql语句,返回结果 stmt.executeQuery(querysql); while (rs.next()) { String name = rs.getString("name"); String age = rs.getString("age"); String adress = rs.getString("adress"); String phone = rs.getString("phone"); System.out.println("姓名"+name +"年龄"+age +"地址"+adress+"电话"+phone); } catch (Exception e) { e.printStackTrace(); }finally{ try { if (stmt!=null) { stmt.close(); } if (conn!=null) { conn.close(); } } catch (SQLException e) { e.printStackTrace(); } } } }
3.myecplise的jdbc配置
如上所示;
区别在于:URL的格式不同
“`
String url = “jdbc:oracle:thin:@localhost:1521:orcl(sid);
“`
4.几种常见的报错:
1. IO 异常: Connection refused(DESCRIPTION=(TMP=)(VSNNUM=186647552)(ERR=12505)(ERROR_STACK=(ERROR=(CODE=12505)(EMFI=4))))
解决方法:数据库名的问题,在需要连接的数据库中运行如下语句
select INSTANCE_NAME from v$instance;将sid改为运行的结果即可
2.Io 异常: Invalid connection string format, a valid format is: “host:port:sid”
URL的格式问题:myecplise是如下格式:
jdbc:oracle:thin:@localhost:1521:orcl