JDBC--數據的查詢準備工作

import java.sql.*;


import javax.rmi.CORBA.Util;
public class Utils {
public static Connection  getConn() throws ClassNotFoundException, SQLException{
//加載數據庫驅動 
Class.forName("oracle.jdbc.driver.OracleDriver");
//連接數據庫的URL
String url="jdbc:oracle:thin:@192.168.1.192:1521:orcl";
//通過驅動管理器獲得數據庫連接
Connection conn=DriverManager.getConnection(url,"hmm","123");
return conn;
}
public static void main(String[] args) throws ClassNotFoundException, SQLException {
// TODO Auto-generated method stub
Connection conn=Utils.getConn();
System.out.println(conn);
}


}

----------------------------------------------------------------



public class UserModel {
private String pid;
private String name;
private String reice;
private String type;

public String getPid() {
return pid;
}


public void setPid(String pid) {
this.pid = pid;
}


public String getName() {
return name;
}


public void setName(String name) {
this.name = name;
}


public String getReice() {
return reice;
}


public void setReice(String reice) {
this.reice = reice;
}


public String getType() {
return type;
}


public void setType(String type) {
this.type = type;
}


public String toString() {
return "UserModel [name=" + name + ", pid=" + pid + ", reice=" + reice
+ ", type=" + type + "]";
}


------------------------------------------------------------------


import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;




public class Test_Query {
public static void main(String[] args) {
List<UserModel> list=query();
for(UserModel o:list){
System.out.println(o);
}
}
/**
* 取得表中所有的數據
* @return 使用UserModel封裝一條數據庫表的記錄,再使用list封裝UserModel
*/
public static List<UserModel> query(){
List<UserModel> list=new ArrayList<UserModel>();
//數據庫連接
Connection conn=null;

try {
//1.通過工具類取得數據庫連接
conn=Utils.getConn();
//2.創建能操作數據庫的Statement對象
Statement stmt=conn.createStatement();
// 創建一個 Statement 對象來將 SQL 語句發送到數據庫。不帶參數的 SQL 語句通常使用 Statement 對象執行。如果多次執行相同的 SQL 語句,使用 PreparedStatement 對象可能更有效。
// Statement 對象表示基本語句,其中將單個方法應用於某一目標和一組參數,以返回結果
String sql="SELECT * FROM product_tab";
//3.執行sql,返回包含數據的結果集對象
ResultSet rs=stmt.executeQuery(sql);
//表示數據庫結果集的數據表,通常通過執行查詢數據庫的語句生成
//處理數據庫返回的結果:將ResultSet轉換成List
while(rs.next()){
String pid=rs.getString("pid");
String name=rs.getString("name");
String reice=rs.getString("reice");
String type=rs.getString("type");

UserModel um=new UserModel();
um.setPid(pid);
um.setName(name);
um.setReice(reice);
um.setType(type);
list.add(um);
}
rs.close();
stmt.close();


} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
finally{
if(conn!=null){
try {
//關閉操作和連接
conn.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}

return list;

}
}


}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章