1.导入驱动包:
a.找到oracle安装目录下的jdbc/lib中的文件classes12.jar;
b.右击你创建的JAVA工程,找到Build path,选择Add External Archives,找到你要导入的包classes12.jar,点击打开就可以引入,引入后在工程下面的ReferencedeLibraries下便能显示这个包。
2.代码测试:
import java.sql.*;
public class oracle
{
String driver = "oracle.jdbc.OracleDriver";
String url="jdbc:oracle:thin:@localhost:1521:orcl";//@主机名:监听端口:数据库实例名称,Attention notes:the port is generally 1521
String name = "system";//登录名
String pwd = "orcl";//登陆密码 private static Statement sql = null;
private static ResultSet rs = null;
private static Connection con = null; public Connection getCon()
{
try
{
Class.forName(driver); //注册oracle数据库驱动
}
catch (ClassNotFoundException e1)
{
System.out.println("驱动加载失败!");
e1.printStackTrace();
}
try
{
con = DriverManager.getConnection(url, name, pwd);//获取连接字符串
}
catch (SQLException e)
{
System.out.println("驱动或数据库连接失败!");
e.printStackTrace();
}
return con;
} public static void main(String[] args)
{
try
{
oracle db = new oracle();
Connection con = db.getCon();
if (con != null)
{
System.out.println("数据库连接成功!");
}
else
{
System.out.println("数据库连接失败!");
}
sql = con.createStatement();
rs = sql.executeQuery("select * from students");
System.out.println("编号\t学号\t姓名\t性别\t出生日期");
while (rs.next())
{
System.out.println(rs.getInt(1)+"\t"+rs.getString(2)+"\t"+rs.getString(3)+"\t"+rs.getString(4)+"\t"+rs.getString(5));
} }
catch(Exception e)
{
e.printStackTrace();
}
}
}
3.测试结果: