JDBC抽取工具类
2019-05-08 / JAVA / 1192 次围观 / 0 次吐槽 /封装的思想
public static void main(String[] args) throws SQLException {
Connection conn = DBUtils.getConnection();
Statement statement = conn.createStatement();
ResultSet resultSet = statement.executeQuery("select * from user");
List<User> list = new ArrayList<User>();
while(resultSet.next()) {
User user = new User();
user.setId(resultSet.getInt("id"));
user.setName(resultSet.getString("name"));
user.setPassword(resultSet.getString("password"));
user.setEmail(resultSet.getString("email"));
user.setBirthday(resultSet.getDate("birthday"));
list.add(user);
}
DBUtils.dbClose(resultSet, statement, conn);
for(User user : list) {
System.out.println(user);
}
}import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class DBUtils {
private static String dbserver = "localhost";
private static String dbport = "3306";
private static String dbusername = "root";
private static String dbpassword = "123456";
private static String dbname = "test1";
static {
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
public static Connection getConnection() throws SQLException {
return DriverManager.getConnection("jdbc:mysql://"+ dbserver +":"+ dbport +"/"+ dbname,dbusername,dbpassword);
}
public static void dbClose(ResultSet resultSet,Statement statement,Connection conn) {
if(resultSet != null) {
try {
resultSet.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if(statement != null) {
try {
statement.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if(conn != null) {
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}import java.util.Date;
public class User {
private int id;
private String name;
private String password;
private String email;
private Date birthday;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public Date getBirthday() {
return birthday;
}
public void setBirthday(Date birthday) {
this.birthday = birthday;
}
@Override
public String toString() {
return "User [id=" + id + ", name=" + name + ", password=" + password + ", email=" + email + ", birthday="
+ birthday + "]";
}
}- 上一篇:JDBC的CURD操作
- 下一篇:SQL注入问题
Powered By Cheug's Blog
Copyright Cheug Rights Reserved.