JDBC(1)JAVA连接数据库之 基础知识学习

java连接数据库

  1. 加载驱动类 导入jar(jar中都是class)

    1. 项目名右键 属性中添加JavaBuildPath
  2. 应该把数据库的连接和资源的关闭包装

  3. 把针对表的操作进行包装。DAO

    1. 一张表会和一个类进行对应
    2. 列会对应属性
    3. 一条记录对应对象
  4. java.sql.Statement====>java,sqp.PreparedStatement

    1. sql语句中的需要传递的值可以用?站位,起到预编译的效果,提高效率。
    2. 防止sql注入
  5. 用PreparedStatement包装UserDao


数据库的简单连接和查询

package lesson1;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;

public class jdbcDemo1 {
    public static void main(String[] args) {
        try {
            // 1.加载驱动类
            Class.forName("oracle.jdbc.driver.OracleDriver");
            // 2.获得连接 java.sql.Connection
            Connection con = DriverManager.getConnection(
                    "jdbc:oracle:thin:@localhost:1521:ORCL", "scott", "tiger");
            // System.out.println(con);
            // 3.执行sql语句 java.sql.Statement
            Statement stmt = con.createStatement();
            // 4.执行sql 查询语句---->查询得到结果集 java.sql.ResultSet
            String sql = "select * from bb_user";
            ResultSet rs = stmt.executeQuery(sql);
            // 5.访问结果集

            while (rs.next()) {
                System.out.println(rs.getInt(1) + "," + rs.getString(2) + ","
                        + rs.getString(3) + "," + rs.getString(4));  

//              System.out.println(rs.getInt("empno")+","+ rs.getString("ename") + ","
//                      + rs.getString("job") + "," + rs.getInt("sal"));
            }
            // 6.关闭资源 ---->异常后面要细致处理
            rs.close();
            stmt.close();
            con.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

数据库操作练习

package lesson1;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;

public class jdbcDemo2 {
    public static void main(String[] args) {
        try {
            Class.forName("oracle.jdbc.driver.OracleDriver");
            Connection con = DriverManager.getConnection(
                    "jdbc:oracle:thin:@localhost:1521:ORCL", "scott", "tiger");
            Statement stmt =con.createStatement();
        //增加一条记录    
//      String sql = "insert into bb_user(id,username,userpass,email) " +
//          "values(1111,'hh','123456','[email protected]')";

//      String sql = "insert into bb_user(id,username,userpass,email) " +
//              "values(1112,'hh1','123456','[email protected]')";

        //修改一条记录
//      String sql  = "update bb_user set username='hhhh' where id=1111";

        //删除一条记录
        String sql = "delete bb_user where id=1001";
        //返回时影响记录的条数
        int n = stmt.executeUpdate(sql);
            System.out.println(n);
            stmt.close();   //关闭相关资源
            con.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

对连接数据库的操作进行包装

配置信息写在properties文件中,方便修改

package lesson1;

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 JdbcUitl {
    private static Properties prop = new Properties();
    static{
        try {
            prop.load(JdbcUitl.class.getResourceAsStream("/database.properties"));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    public static Connection getConn(){
        try {
            Class.forName(prop.getProperty("driverClass"));
            Connection con = DriverManager.getConnection(
                    prop.getProperty("url"),prop.getProperty("user"),prop.getProperty("pass"));

            return con;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 资源关闭
     * @param con
     * @param stmt
     * @param rs
     */
    public static void close(Connection con,Statement stmt,ResultSet rs){
        if(rs!=null)
            try {
                rs.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        if(stmt!=null)
            try {
                stmt.close();
            } catch (SQLException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        if(con!=null)
            try {
                con.close();
            } catch (SQLException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
    }
}
package lesson1;

import java.sql.Connection;
import java.sql.Statement;

public class jdbcDemo3 {
    public static void main(String[] args) {
        try {
            Connection con = JdbcUitl.getConn();
            Statement stmt = con.createStatement();
            //增加一条记录
        /*  int id=1113;
            String pass="zsan";
            String name="zhangsan";
            String email="[email protected]";
            String sql="insert into bb_user(id,username,userpass,email) "+
                    "values("+id+",'"+name+"','"+pass+"','"+email+"')";
            int n=stmt.executeUpdate(sql);
            System.out.println(n);*/

            //修改记录
            int id=1112;
            String pass="zzzs123";
            String email = "[email protected]";
            String sql = "update bb_user set userpass='"+pass+"',email='"+email+"'" +
                    "where id="+id+"";
            stmt.executeUpdate(sql);
//          stmt.close();
//          con.close();
            JdbcUitl.close(con, stmt, null);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

对“增删改查”操作进行包装

创建和数据结构对应的user类

package lesson1;

public class User {
    private int id;
    private String username;
    private String userpass;
    private String email;
    public User (){}

    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 getUserpass() {
        return userpass;
    }
    public void setUserpass(String userpass) {
        this.userpass = userpass;
    }
    public String getEmail() {
        return email;
    }
    public void setEmail(String email) {
        this.email = email;
    }


    public User(int id, String username, String userpass, String email) {
        super();
        this.id = id;
        this.username = username;
        this.userpass = userpass;
        this.email = email;
    }
    @Override
    public String toString() {
        return "User [id=" + id + ", username=" + username + ", userpass="
                + userpass + ", email=" + email + "]";
    }

}

包装方法

package lesson1;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;

import javax.jws.soap.SOAPBinding.Use;

public class UserDao {
    /**
     * 增加一条记录
     * @param user
     * @return
     */
    public int addUser(User user) {
        Connection con = null;
        Statement stmt = null;
        int n = 0;
        try {
            con = JdbcUitl.getConn();
            stmt = con.createStatement();
            String sql = "insert into bb_user(id,username,userpass,email)"
                    + "values(" + user.getId() + ",'" + user.getUsername()
                    + "','" + user.getUserpass() + "','" + user.getEmail()
                    + "')";
            n = stmt.executeUpdate(sql);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            JdbcUitl.close(con, stmt, null);
        }
        return n;
    }

    /**
     * 查询所有记录
     * @return
     */
    public List getAll() {
        Connection con = null;
        Statement stmt = null;
        ResultSet rs = null;

        ArrayList users = new ArrayList();
        try {
            con = JdbcUitl.getConn();
            stmt = con.createStatement();
            String sql = "select * from bb_user";
            rs = stmt.executeQuery(sql);
            while (rs.next()) {
                User user = new User();
                user.setId(rs.getInt("id"));
                user.setUsername(rs.getString("username"));
                user.setUserpass(rs.getString("userpass"));
                user.setEmail(rs.getString("email"));
                users.add(user);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            JdbcUitl.close(con, stmt, rs);
        }
        return users;
    }

    /**
     * 修改用户信息
     * @param user
     * @return
     */
    public int updateUser(User user) {
        Connection con = null;
        Statement stmt = null;
        int n = 0;
        try {
            con = JdbcUitl.getConn();
            stmt = con.createStatement();
            String sql = "update bb_user set username='" + user.getUsername()
                    + "',userpass='" + user.getUserpass() + "',email='"
                    + user.getEmail() + "'where id =" + user.getId();
            n=stmt.executeUpdate(sql);
        } catch (Exception e) {
            e.printStackTrace();
        }finally{
            JdbcUitl.close(con, stmt, null);
        }
        return n;
    }

    /**
     * 根据主键查询一条记录
     * @param id
     * @return
     */
    public User findById(int id){
        Connection con =null;
        Statement stmt = null;
        ResultSet rs = null;
        User user = null;
        try {
            con=JdbcUitl.getConn();
            stmt=con.createStatement();
            String sql = "select*from bb_user where id="+id;
            rs = stmt.executeQuery(sql);
            if(rs.next()){
                user = new User();
                user.setId(rs.getInt("id"));
                user.setUsername(rs.getString("username"));
                user.setUserpass(rs.getString("userpass"));
                user.setEmail(rs.getString("email"));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }finally{
            JdbcUitl.close(con, stmt, rs);
        }
        return user;
    }

    /**
     * User对象中除主键外,哪个属性有值,就根据哪个属性查询
     * @param user
     * @return
     */
    public List findBy(User user){
        Connection con = null;
        Statement stmt = null;
        ResultSet rs = null;
        ArrayList users = new ArrayList();
        String sql ="select*from bb_user where 1=1";
        String username = user.getUsername();
        if(username!=null)
            sql +=" and username='"+username+"'";
        String userpass = user.getUserpass();
        if(userpass!=null)
            sql +=" and userpass='"+userpass+"'";
        String email = user.getEmail();
        if(email!=null)
            sql +=" and email='"+email+"'"; 
        System.out.println(sql);
        try {
            con = JdbcUitl.getConn();
            stmt = con.createStatement();
            rs=stmt.executeQuery(sql);
            while(rs.next()){
                User user2 = new User();
                user2.setId(rs.getInt("id"));
                user2.setUsername(rs.getString("username"));
                user2.setUserpass(rs.getString("userpass"));
                user2.setEmail(rs.getString("email"));
                users.add(user2);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }finally{
            JdbcUitl.close(con, stmt, rs);
        }
        return users;
    }
    public int deleteUser(int id){
        Connection con = null;
        Statement stmt = null;
        int n = 0;
        try {
            con =JdbcUitl.getConn();
            stmt =con.createStatement();
            String sql = "delete bb_user where id="+id;
            n= stmt.executeUpdate(sql);
        } catch (Exception e) {
            e.printStackTrace();
        }finally{
            JdbcUitl.close(con, stmt, null);
        }
        return n; 
    }
}

测试

package lesson1;

import java.util.List;

public class jdbcDemo4 {

    public static void main(String[] args) {
        //测试增加提条记录
        UserDao ud =new UserDao();

//      User user = new User(1115, "yq", "12345", "[email protected]");
//      int n = ud.addUser(user);
//      System.out.println(n);  


        //测试查询所有
//      List users = ud.getAll();
//      for (User user : users) {
//          System.out.println(user);
//      }

        //测试根据主键来查询记录
/*      User user = ud.findById(1111);
        if(user!=null)
        System.out.println(user);*/
        //测试修改
/*      user.setUsername("lisi_name");
        user.setUserpass("123lisi");
        ud.updateUser(user);    */

        //测试不定查询
//      User user = new User();
//      user.setUsername("zhangsan");
//      user.setUserpass("12345");  
//      List users= ud.findBy(user);
//      for (User user2 : users) {
//          System.out.println(user2);
//      }

        //测试删除
//      User user = ud.findById(1111);
//      ud.deleteUser(user.getId());

        int n=ud.deleteUser(1001);
        System.out.println(n);

    }
}

PreparedStatement类的使用

package lesson1;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.Statement;


public class JdbcDemo5 {
    public static void main(String[] args) {
        try {
            Connection con = JdbcUitl.getConn();
/*          Statement stmt = con.createStatement();
            int id = 1001;
            String name = "lisi";
            String pass = "lisi123";
            String email = "[email protected]";

            String sql ="insert into bb_user(id,username,userpass,email) "+
                    "values("+id+",'"+name+"','"+pass+"','"+email+"')";
            int n = stmt.executeUpdate(sql);
            JdbcUitl.close(con, stmt, null);    */
            String sql="insert into bb_user(id,username,userpass,email)values(?,?,?,?)";
            PreparedStatement pstmt = con.prepareStatement(sql);
            int id = 1001;
            String name = "lisi";
            String pass = "lisi123";
            String email = "[email protected]";
            pstmt.setInt(1, id);
            pstmt.setString(2, name);
            pstmt.setString(3, pass);
            pstmt.setString(4, email);
            int n =pstmt.executeUpdate();
            System.out.println(n);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

sql注入测试

package lesson1;
/**
 * 测试 sql注入
 */
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;

public class JdebDemo6 {
    public static void main(String[] args) {
        try {
            Connection con = JdbcUitl.getConn();
            Statement stmt = con.createStatement();
            String name = "zhangsan";
            //如果密码是类似这样的值, 那么sql语句恒成立
            String pass = "123'or'a'='a";
    /*      String sql = "select*from bb_user where username='" + name
                    + "'and userpass='" + pass + "'";
            System.out.println(sql);
            ResultSet rs=stmt.executeQuery(sql);
            System.out.println(rs.next());  */
            PreparedStatement pstmt = con.prepareStatement("select*from bb_user where username=? and userpass=?");
            pstmt.setString(1, name);
            pstmt.setString(2, pass);
            ResultSet rs = pstmt.executeQuery();
            System.out.println(rs.next()); 
        } catch (Exception e) {
            e. printStackTrace();
        }
    }
}

重新包装方法

package lesson1;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;

import javax.jws.soap.SOAPBinding.Use;

public class UserDaoBean {
    /**
     * 增加一条记录
     * @param user
     * @return
     */
    public int addUser(User user) {
        Connection con = null;
        PreparedStatement pstmt = null;
        int n = 0;
        try {
            con = JdbcUitl.getConn();
            String sql = "insert into bb_user(id,username,userpass,email)values(?,?,?,?)";
            pstmt = con.prepareStatement(sql);
            pstmt.setInt(1, user.getId());
            pstmt.setString(2, user.getUsername());
            pstmt.setString(3, user.getUserpass());
            pstmt.setString(4,user.getEmail());
            n=pstmt.executeUpdate();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            JdbcUitl.close(con, pstmt, null);
        }
        return n;
    }

    /**
     * 查询所有记录
     * @return
     */
    public List getAll() {
        Connection con = null;
        PreparedStatement pstmt = null;
        ResultSet rs = null;

        ArrayList users = new ArrayList();
        try {
            con = JdbcUitl.getConn();
            pstmt = con.prepareStatement("select * from bb_user");
            rs = pstmt.executeQuery();
            while (rs.next()) {
                User user = new User();
                user.setId(rs.getInt("id"));
                user.setUsername(rs.getString("username"));
                user.setUserpass(rs.getString("userpass"));
                user.setEmail(rs.getString("email"));
                users.add(user);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            JdbcUitl.close(con, pstmt, rs);
        }
        return users;
    }

    /**
     * 修改用户信息
     * @param user
     * @return
     */
    public int updateUser(User user) {
        Connection con = null;
        PreparedStatement pstmt = null;
        int n = 0;
        try {
            con = JdbcUitl.getConn();
            String sql = "update bb_user set username=?,userpass=?,email=? where id=?";
            pstmt = con.prepareStatement(sql);
            pstmt.setString(1, user.getUsername());
            pstmt.setString(2, user.getUserpass());
            pstmt.setString(3, user.getEmail());
            pstmt.setInt(4, user.getId());
            n=pstmt.executeUpdate();
        } catch (Exception e) {
            e.printStackTrace();
        }finally{
            JdbcUitl.close(con, pstmt, null);
        }
        return n;
    }

    /**
     * 根据主键查询一条记录
     * @param id
     * @return
     */
    public User findById(int id){
        Connection con =null;
        PreparedStatement pstmt = null;
        ResultSet rs = null;
        User user = null;
        try {
            con=JdbcUitl.getConn();
            String sql = "select*from bb_user where id="+id;    
            pstmt = con.prepareStatement(sql);
            rs = pstmt.executeQuery();
            if(rs.next()){
                user = new User();
                user.setId(rs.getInt("id"));
                user.setUsername(rs.getString("username"));
                user.setUserpass(rs.getString("userpass"));
                user.setEmail(rs.getString("email"));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }finally{
            JdbcUitl.close(con, pstmt, rs);
        }
        return user;
    }

    /**
     * User对象中除主键外,哪个属性有值,就根据哪个属性查询
     * @param user
     * @return
     */
    public List findBy(User user){
        Connection con = null;
        Statement stmt = null;
        ResultSet rs = null;
        ArrayList users = new ArrayList();
        String sql ="select*from bb_user where 1=1";
        String username = user.getUsername();
        if(username!=null)
            sql +=" and username='"+username+"'";
        String userpass = user.getUserpass();
        if(userpass!=null)
            sql +=" and userpass='"+userpass+"'";
        String email = user.getEmail();
        if(email!=null)
            sql +=" and email='"+email+"'"; 
        System.out.println(sql);
        try {
            con = JdbcUitl.getConn();
            stmt = con.createStatement();
            rs=stmt.executeQuery(sql);
            while(rs.next()){
                User user2 = new User();
                user2.setId(rs.getInt("id"));
                user2.setUsername(rs.getString("username"));
                user2.setUserpass(rs.getString("userpass"));
                user2.setEmail(rs.getString("email"));
                users.add(user2);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }finally{
            JdbcUitl.close(con, stmt, rs);
        }
        return users;
    }


    public int deleteUser(int id){
        Connection con = null;
        PreparedStatement pstmt = null;
        int n = 0;
        try {
            con =JdbcUitl.getConn();        
            String sql = "delete bb_user where id="+id;
            pstmt = con.prepareStatement(sql);
            n=pstmt.executeUpdate();
        } catch (Exception e) {
            e.printStackTrace();
        }finally{
            JdbcUitl.close(con, pstmt, null);
        }
        return n; 
    }
}

测试

package lesson1;

import java.util.List;

public class JdbcDemo7 {
    public static void main(String[] args) {
        UserDaoBean udb = new UserDaoBean();
        //添加一条记录测试
    /*  User user = new User(2000,"wp","123","[email protected]");
        int n=udb.addUser(user);
        System.out.println(n);  */

        //查询全部测试
    /*  
        List users = udb.getAll();
        for (User user : users) {
            System.out.println(user);  
        }
    */  
        //根据ID查询 并修改
    /*  User user = udb.findById(2000);
        System.out.println(user);
        user.setUsername("xxxx");
        user.setUserpass("12xxxxx");
        udb.updateUser(user);
    */
        //删除信息
        udb.deleteUser(2000);
    }
}

写在最后:JDBC基础知识学习了一下。做此总结

你可能感兴趣的:(java学习,数据库)