DB.java
上传用户:huaxinghn
上传日期:2022-04-20
资源大小:673k
文件大小:3k
- package lilin.dao;
- import java.sql.Connection;
- import java.sql.ResultSet;
- import java.sql.SQLException;
- import java.sql.Statement;
- import java.sql.DriverManager;
- import java.util.ArrayList;
- import java.util.List;
- import java.sql.PreparedStatement;
- import lilin.bean.User;
- public class DB {
- private Connection conn = null;
- private Statement stem = null;
- private ResultSet rs = null;
- private PreparedStatement ps = null;
- private boolean is_true = false;
- private String url = "jdbc:mysql://localhost:3306/lilin";
- private String name = "root";
- private String pwd = "root";
- public DB() throws ClassNotFoundException, SQLException{
- Class.forName("com.mysql.jdbc.Driver");
- conn = DriverManager.getConnection(url,name,pwd);
- }
-
- public List select_All() throws SQLException{
- List user_list = new ArrayList();
- stem = conn.createStatement();
- rs = stem.executeQuery("select * from users");
- while(rs.next()){
- User user_ref = new User();
- user_ref.setId(rs.getInt("id"));
- user_ref.setUsername(rs.getString("username"));
- user_ref.setPassword(rs.getString("password"));
-
- user_list.add(user_ref);
- }
- return user_list;
- }
-
- public boolean insert_User(String name,String password) throws SQLException{
- ps = conn.prepareStatement("insert into users(username,password) values(?,?)");
- ps.setString(1, name);
- ps.setString(2,password);
- int result = ps.executeUpdate();
- is_true = result > 0?true:false;
- return is_true;
- }
-
- public boolean delete_User(int id) throws SQLException{
- ps = conn.prepareStatement("delete from users where id=?");
- ps.setInt(1, id);
- int result = ps.executeUpdate();
- is_true = result > 0?true:false;
- return is_true;
-
- }
-
- public int select_UserByNamePwd(String name,String password) throws SQLException{
- int id = 0;
- ps = conn.prepareStatement("select * from users where username=? and password=?");
- ps.setString(1, name);
- ps.setString(2, password);
-
- rs = ps.executeQuery();
-
- while(rs.next()){
- id = rs.getInt("id");
- }
- return id;
- }
-
- public boolean update_User(int id,String type,String value) throws SQLException{
- //System.out.println("update users set "+type+"=? where id=?");
- ps = conn.prepareStatement("update users set "+type+"=? where id=?");
- ps.setString(1, value);
- ps.setInt(2, id);
-
- int result = ps.executeUpdate();
- is_true = result > 0?true:false;
- return is_true;
- }
- public void closeAll(){
- if(conn != null){
- try {
- conn.close();
- } catch (SQLException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- }
- }
- }