Java訪問Oracle資料庫代碼

來源:互聯網
上載者:User

功能:將資料庫中的資料讀到java類cube中,並計算出正方體的體積。

1.使用PL/SQL Developor設計一個表格,名為first;
Table -> new Table,設計資料表空間,與欄位的大小,以及主鍵;
Table -> first -> edit data,填入所需要的資料,則一個表格就產生了。

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;
}
}

相關文章

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.