Java Web学习总结(九) JDBC

Java Web学习总结(九) JDBC

  1. 什么是JDBC

    JDBC的全称是Java数据库连接(Java Databse Connectivity),它是一套用于执行SQL语句的Java API.

  2. JDBC的一般步骤

    1. 加载驱动

    2. 连接数据库

    3. 执行SQL代码

      1. 初始化SQL代码
      2. 构建SQL代码
      3. 执行SQL代码
    4. 关闭连接

    5. 示例

      1. 创建示例数据库

        CREATE DATABASE jc;
        USE jc;
        CREATE TABLE `user` (
          `Id` int(11) NOT NULL AUTO_INCREMENT,
          `username` varchar(20) DEFAULT NULL,
          `password` varchar(20) DEFAULT NULL,
          PRIMARY KEY (`Id`)
        )engine = InnoDB DEFAULT CHARSET=utf8;
        USE jc;
        insert into user (username, password) values('zs', '123');
        insert into user (username, password) values('ls', '123');
        insert into user (username, password) values('ww', '123');
        
      2. 创建实体类User

        package ink.heat.entity;
        
        public class User {
                   
        	private int id;
        	private String username;
        	private String password;
        	public User() {
                   }
        	public User(String username, String password) {
                   
        		super();
        		this.username = username;
        		this.password = password;
        	}
        	public User(int id, String username, String password) {
                   
        		super();
        		this.id = id;
        		this.username = username;
        		this.password = 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;
        	}
        	@Override
        	public String toString() {
                   
        		return "User [id=" + id + ", username=" + username + ", password=" + password + "]";
        	}
        	
        }
        
      3. 创建UserDao类(对User的增、删、改、查操作)

        package ink.heat.dao;
        
        import java.sql.Connection;
        import java.sql.DriverManager;
        import java.sql.PreparedStatement;
        import java.sql.ResultSet;
        import java.sql.SQLException;
        import java.util.ArrayList;
        import java.util.List;
        
        import ink.heat.entity.User;
        
        public class UserDao {
                   
        	/**
        	 * 对User的增加, 删除, 修改, 查询
        	 */
        	private Connection conn = null;
        	private PreparedStatement pstat = null;
        	private ResultSet rs = null;
        	private String driver = "com.mysql.jdbc.Driver";
        	private String url = "jdbc:mysql://localhost:3306/jc?characterEncoding=UTF-8";
        	private String dbUsername = "root";
        	private String dbPassword = "123456";
        	
        	/**
        	 * 	获得数据库链接
        	 * @return Connection 对象
        	 * @throws ClassNotFoundException
        	 * @throws SQLException
        	 */
        	public Connection getConnection() throws ClassNotFoundException, SQLException {
                   
        		Class.forName(driver);//1.加载驱动
        		return (Connection) DriverManager.getConnection(url, dbUsername, dbPassword);//2.获得数据库连接
        	}
        	
        	/**
        	 * 	关闭所有连接
        	 */
        	public void closeAll() {
                   
        		if (conn != null) {
                   
        			try {
                   
        				conn.close();
        			} catch (SQLException e) {
                   
        				e.printStackTrace();
        			}
        		}
        		if (pstat != null) {
                   
        			try {
                   
        				pstat.close();
        			} catch (SQLException e) {
                   
        				e.printStackTrace();
        			}
        		}
        		if (rs != null) {
                   
        			try {
                   
        				rs.close();
        			} catch (SQLException e) {
                   
        				e.printStackTrace();
        			}
        		}
        	}
        	
        	/**
        	 * 	打印数据库返回的users
        	 * @param users
        	 */
        	public void printUsers(List<User> users) {
                   
        		for (User user : users) {
                   
        			System.out.println(user);
        		}
        	}
        	
        	/**
        	 * 	查询所有对象
        	 * @return 所有用户对象
        	 */
        	public List<User> queryAllUser() {
                   
        		List<User> users = new ArrayList<User>();
        		try{
                   
        			conn = getConnection();
        			String sql = "select * from user";
        			pstat = conn.prepareStatement(sql);//初始化SQL代码
        			rs = pstat.executeQuery();//执行SQL代码
        			while (rs.next()) {
                   
        				User user = new User();
        				user.setId(rs.getInt("id"));
        				user.setUsername(rs.getString("username"));
        				user.setPassword(rs.getString("password"));
        				users.add(user);
        			}
        		} catch (ClassNotFoundException e) {
                   
        			e.printStackTrace();
        		} catch (SQLException e) {
                   
        			e.printStackTrace();
        		} finally {
                   
        			closeAll();
        		}
        		return users;
        	}
        	
        	/**
        	 * 	增加一个User
        	 * @param user
        	 * @return
        	 */
        	public int addUser(User user) {
                   
        		int result = -1;
        		try {
                   
        			conn = getConnection();
        			String sql = "insert into user (username, password) values(?,?)";
        			pstat = conn.prepareStatement(sql);
        			pstat.setString(1, user.getUsername());
        			pstat.setString(2, user.getPassword());
        			result = pstat.executeUpdate();
        		} catch (ClassNotFoundException e) {
                   
        			e.printStackTrace();
        		} catch (SQLException e) {
                   
        			e.printStackTrace();
        		} finally {
                   
        			closeAll();
        		}
        		return result;
        	}
        	
        	/**
        	 * 	更新一个用户
        	 * @param user
        	 * @return
        	 */
        	public int updateUser(User user) {
                   
        		int result = -1;
        		try {
                   
        			conn = getConnection();
        			String sql = "update user set username=?,password=? where id=?";
        			pstat = conn.prepareStatement(sql);
        			pstat.setString(1, user.getUsername());
        			pstat.setString(2, user.getPassword());
        			pstat.setInt(3, user.getId());
        			result = pstat.executeUpdate();
        		} catch (ClassNotFoundException e) {
                   
        			e.printStackTrace();
        		} catch (SQLException e) {
                   
        			e.printStackTrace();
        		} finally {
                   
        			closeAll();
        		}
        		return result;
        	}
        	
        	/**
        	 * 	删除一个用户
        	 * @param id
        	 * @return
        	 */
        	public int deleteUser(int id) {
                   
        		int result = -1;
        		try {
                   
        			conn = getConnection();
        			String sql = "delete from user where id=?";
        			pstat = conn.prepareStatement(sql);
        			pstat.setInt(1, id);
        			result = pstat.executeUpdate();
        		} catch (ClassNotFoundException e) {
                   
        			e.printStackTrace();
        		} catch (SQLException e) {
                   
        			e.printStackTrace();
        		} finally {
                   
        			closeAll();
        		}
        		return result;
        	}
        }
        
        
      4. 创建测试类

        package ink.heat.test;
        import java.util.List;
        
        import ink.heat.dao.UserDao;
        import ink.heat.entity.User;
        
        public class JDBCTest {
                   
        
        	public static void main(String[] args) {
                   
        		
        		List<User> users = null;
        		UserDao dao = new UserDao();
        		//查询
        		System.out.println("--------【查询】- - - - - - -  ");
        		users = dao.queryAllUser();
        		dao.printUsers(users);
        		
        		
        		
        		System.out.println("--------【增加】- - - - - - -  ");
        		User u = new User("zl", "123");
        		dao.addUser(u);
        		users = dao.queryAllUser();
        		dao.printUsers(users);
        		
        		
        		
        		System.out.println("--------【修改】- - - - - - -  ");
        		User u1 = new User(4, "zl", "1234");
        		dao.updateUser(u1);
        		users = dao.queryAllUser();
        		dao.printUsers(users);
        		
        		
        		
        		System.out.println("--------【删除】- - - - - - -  ");
        		dao.deleteUser(1);
        		users = dao.queryAllUser();
        		dao.printUsers(users);
        	}
        
        }
        
        
  3. 关于Statement和PreparedStatement

    Statement 由于存在使用不方便以及存在SQL注入问题, 所以不推荐使用。

  4. 创建DBUtils

    上面的例子中,已经将重复的部分代码提取来作为方法了, 但是这些方法都只对UserDao有效,将来项目Dao层多时, 代码又会重复, 所以将它们提取到一个工具类是十分有必要的。

    package ink.heat.util;
    
    import java.io.IOException;
    import java.io.InputStream;
    import java.sql.Connection;
    import java.sql.DriverManager;
    import java.sql.ResultSet;
    import java.sql.SQLException;
    import java.sql.Statement;
    import java.util.Properties;
    
    public class DBUtils {
           
    	private static String driver;
    	private static String url;
    	private static String dbUsername;
    	private static String dbPassword;
    	
    	static {
           
    		Properties properties = new Properties();
    		InputStream in = DBUtils.class.getClassLoader().getResourceAsStream("db.properties");
    		try {
           
    			properties.load(in);
    			driver = properties.getProperty("driver");
    			url = properties.getProperty("url");
    			dbUsername = properties.getProperty("dbUsername");
    			dbPassword = properties.getProperty("dbPassword");
    		} catch (IOException e) {
           
    			// TODO Auto-generated catch block
    			e.printStackTrace();
    		}
    	}
    	
    	public static Connection getConnection() throws ClassNotFoundException, SQLException {
           
    		Class.forName(driver);
    		return (Connection) DriverManager.getConnection(url, dbUsername, dbPassword);
    	}
    	
    	public static void closeAll(Connection conn, Statement stat, ResultSet rs) {
           
    		if (conn != null) {
           
    			try {
           
    				conn.close();
    			} catch (SQLException e) {
           
    				e.printStackTrace();
    			}
    		}
    		if (stat != null) {
           
    			try {
           
    				stat.close();
    			} catch (SQLException e) {
           
    				e.printStackTrace();
    			}
    		}
    		if (rs != null) {
           
    			try {
           
    				rs.close();
    			} catch (SQLException e) {
           
    				e.printStackTrace();
    			}
    		}
    	}
    }
    

    在src目录下新建db.properties文件, 文件内容如下:

    driver=com.mysql.jdbc.Driver
    url=jdbc:mysql://localhost:3306/jc?characterEncoding=UTF-8
    dbUsername=root
    dbPassword=123456
    

你可能感兴趣的:(Java,Web,javaweb)