JDBC--数据的查询准备工作

来源:互联网 发布:windows vista ghost 编辑:程序博客网 时间:2024/05/21 21:39
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;

}
}


}

原创粉丝点击