天天搞NC财务,很多基础快忘了,现在每天复习一点点,争取盲写代码能很迅速~
BaseDao
package util;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
public class BaseDao {
private final static String DRIVER="org.gjt.mm.mysql.Driver";
private final static String URL="jdbc:mysql://localhost:3306/gym";
private final static String USERNAME="root";
private final static String PASSWORD="admin";
public static Connection getConn(){
Connection con =null;
try {
Class.forName(DRIVER);
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
try {
con = DriverManager.getConnection(URL, USERNAME, PASSWORD);
} catch (SQLException e) {
e.printStackTrace();
}
return con;
}
public static void CloseAll(ResultSet rs,PreparedStatement ps,Connection con){
if(rs!=null){
try {
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
rs=null;
}
if(ps!=null){
try {
ps.close();
} catch (SQLException e) {
e.printStackTrace();
}
ps=null;
}
try {
if(con!=null && !(con.isClosed())){
con.close();
con=null;
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
UserImpl
package impl;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import util.BaseDao;
import vo.User;
public class UserImpl {
ResultSet rs=null;
PreparedStatement ps=null;
Connection con=null;
public ArrayList<User> SelectUser(){
ArrayList<User> list =new ArrayList<User>();
StringBuffer sql=new StringBuffer();
sql.append("select id,username,password from user ");
con=BaseDao.getConn();
try {
ps=con.prepareStatement(sql.toString());
rs=ps.executeQuery();
User u=null;
while(rs.next()){
u=new User();
u.setId(rs.getInt("id"));
u.setUsername(rs.getString("username"));
u.setPassword(rs.getString("password"));
list.add(u);
}
} catch (SQLException e) {
e.printStackTrace();
}finally{
BaseDao.CloseAll(rs, ps, con);
}
return list;
}
}
User
package vo;
public class User {
private int id;
private String username;
private String password;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
Test
package test;
import java.util.ArrayList;
import java.util.Iterator;
import vo.User;
import impl.UserImpl;
public class Test {
public static void main(String[] args) {
UserImpl ud=new UserImpl();
ArrayList<User> list=ud.SelectUser();
Iterator<User> iter=list.iterator();
User u =null;
while(iter.hasNext()){
u=new User();
u=iter.next();
System.out.println(u.getId()+","+u.getUsername()+","+u.getPassword());
}
}
}