2013年7月14日-Java連接Oracle數據庫
DataBaseConn:
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package query;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
import java.sql.DriverManager;
/**
*
* @author Administrator
*/
public class DataBaseConn {
public DataBaseConn(){}
private static String url = "jdbc:oracle:thin:@localhost:1521:ccgis";
private static String name = "name";
private static String password = "password";
public static Connection getConn(){
Connection con = null;
try{
Class.forName("oracle.jdbc.driver.OracleDriver");
con = DriverManager.getConnection(url,name,password);
}
catch(Exception e){
}
return con;
}
public static void close(Connection con,Statement sm,ResultSet rs){
try{
if(con != null){
con.close();
}
if(sm !=null){
sm.close();
}
if(rs != null){
rs.close();
}
}
catch(Exception e){
e.printStackTrace();
}
}
}
GetData:
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package query;
/**
*
* @author Administrator
*/
public class GetData {
public String name;
public String phone;
public String address;
public String getName(){
return this.name;
}
public String getPhone(){
return this.phone;
}
public String getAddress(){
return this.address;
}
public void setName(String name){
this.name = name;
}
public void setPhone(String phone){
this.phone = phone;
}
public void setAddress(String address){
this.address = address;
}
}
Query:
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package query;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.ArrayList;
import query.DataBaseConn;
import query.GetData;
/**
*
* @author Administrator
*/
public class Query {
public ArrayList findAll(){
Connection con = null;
Statement sm = null;
ResultSet rs = null;
String sql = "select * from 用戶名.表名";
ArrayList list = new ArrayList();
try{
con = DataBaseConn.getConn();
sm = con.prepareStatement(sql);
rs = sm.executeQuery(sql);
while(rs.next()){
GetData obj = new GetData();
obj.setName(rs.getString(1));
obj.setPhone(rs.getString(2));
obj.setAddress(rs.getString(3));
list.add(obj);
}
}
catch(Exception e){
e.printStackTrace();
}finally{
try{
DataBaseConn.close(con, sm, rs);
}catch(Exception e){
e.printStackTrace();
}
return list;
}
}
public static void main(String[] args){
Query q = new Query();
ArrayList list = q.findAll();
for(int i = 0;i <list.size();i++){
GetData gd = (GetData)list.get(i);
System.out.println(gd.getName()+"\t"+gd.getPhone()+"\t"+gd.getAddress());
}
}
}
最後更新:2017-04-03 16:48:34