Java访问Oracle数据库代码


功能:将数据库中的数据读到java类cube中,并计算出正方体的体积。

1.使用PL/SQL Developor设计一个表格,名为first;
Table -> new Table,设计表空间,与字段的大小,以及主键;
Table -> first -> edit data,填入所需要的数据,则一个表格就生成了。

Java访问Oracle数据库代码

2.使用java代码访问Oracle数据库,代码如下:
import java.sql.*;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Vector;


public class Test {
static Vector<Cube> CubeObjects = new Vector<Cube>();
public static void main(String[] args) throws ClassNotFoundException, SQLException{
String driver = "oracle.jdbc.driver.OracleDriver";
String strUrl = "jdbc:oracle:thin:@a9ae3e7c1051465:1521:idpdb";//idpdb为数据库名称
Connection conn = null;
ResultSet rsResult=null;
Statement stmt=null;
Class.forName(driver);
//第二个参数为数据库用户名,第三个参数为数据库密码
conn = DriverManager.getConnection(strUrl,"idp_pub_m","idpapp");
stmt=conn.createStatement();
rsResult=stmt.executeQuery("select * from first");
while(rsResult.next()){
Cube cub = new Cube(rsResult.getInt(1),rsResult.getInt(2),                                                                         rsResult.getInt(3),rsResult.getInt(4));
CubeObjects.add(cub);
}
int i = 0;
for(Cube cube:CubeObjects){
System.out.println("矩形次序"  + ++i + " : "+ calculate(cube));
}
}
static int calculate(Cube cube){
try{
if(cube.Height == cube.Length && cube.Length==cube.Width){
return cube.Height*cube.Length*cube.Width;
}else{
throw new Exception("不是正方体");
}
}catch(Exception e){
System.out.println(e.getMessage());
}
return 0;
   }
}


class Cube{
int ID = 0;
int Length = 0;
int Width = 0;
int Height = 0;
public Cube(int ID,int Length, int Width, int Height){
this.ID = ID;
this.Length = Length;
this.Width = Width;
this.Height = Height;
}
}

相关内容