会员可以在此提问,百战程序员老师有问必答
对大家有帮助的问答会被标记为“推荐”
看完课程过来浏览一下别人提的问题,会帮你学得更全面
截止目前,同学们一共提了 132359个问题
JAVA 全系列/第三阶段:数据库编程/MySQL数据库的使用 1681楼
JAVA 全系列/第三阶段:数据库编程/MySQL数据库的使用 1682楼
JAVA 全系列/第三阶段:数据库编程/Oracle 数据库的使用 1683楼

1651156283(1).png

UsersDao

public interface UsersDao extends BaseDao {

    /**
     * 根据用户Id查询用户
     */
    Users selectUsersById(int userid) throws ApplicationException;

    /**
     * 修改用户信息
     * @param users
     * @return
     */
    int updateUsersById(Users users) ;
    /**
     * 根据用户姓名模糊查询
     */
    List<Users> selectUsersByLikeName(String username);
}

UsersDaoImpl

public class UsersDaoImpl extends BaseDaoImpl implements UsersDao {

    /**
     * 根据用户ID查询用户
     * @param userid
     * @return
     */

    @Override
    public Users selectUsersById(int userid) throws ApplicationException {
        Connection conn = null;
        PreparedStatement ps = null;
        ResultSet rs = null ;
        Users users = null;
        try {
            conn = jdbcUtill.getConnection();
            ps = conn.prepareStatement("select * from users where userid = ?");
            ps.setInt(1,userid);
            rs = ps.executeQuery();
            while (rs.next()){
                //手动orm映射
                users  = new Users();
                users.setUserid(rs.getInt("userid"));
                users.setUsername(rs.getString("username"));
                users.setUserage(rs.getInt("userage"));
            }


        }catch (Exception e){
            e.printStackTrace();
            throw new ApplicationException(e.getMessage());


        }finally {
            jdbcUtill.closeConnection(rs,ps,conn);
        }

        return users;
    }

    /**
     * 修改用户信息
     * @param
     * @return
     */

    @Override
    public int updateUsersById(Users users) {
        String sql = "update users set userage = ? where userid = ?";
        Object[] param = new Object[]{users.getUserage(),users.getUserid()};
        return this.executeUpdate(sql,param);
    }

    @Override
    public List<Users> selectUsersByLikeName(String username) {
        String sql = "select * from users where username like ?";
        Object[] param =new Object[]{"%"+username+"%"};
        return this.select(sql,param,Users.class);
    }


}

BaseDao

public interface BaseDao {
    /**
     * 通用的Dml操作方法
     */
    int executeUpdate(String sql,Object[] param) ;

    /**
     * 通用查询方法
     *
     */
   <T> List<T> select(String sql,Object[] param,Class<T> clazz);
}

BaseDaoImpl

public class BaseDaoImpl implements BaseDao {
    /**
     * 通用的Dml的操作
     */
    @Override
    public int executeUpdate(String sql, Object[] param) {
        Connection connection = null;
        PreparedStatement ps = null;
        int row = 0;
        try {
            connection = jdbcUtill.getConnection();
            ps = connection.prepareStatement(sql);
            //得到参数的个数
            ParameterMetaData pd = ps.getParameterMetaData();
            for (int i = 0;i<pd.getParameterCount();i++){
                ps.setObject(i+1,param[i]);
            }
            row = ps.executeUpdate();

        }catch (Exception e){
            e.printStackTrace();
            

        }finally {
            jdbcUtill.closeResource((Statement) ps,connection);
        }

        return row;
    }

    /**
     * 通用查询方法
     * @param sql
     * @param param
     * @param
     * @param <T>
     * @return
     */

    @Override
    public <T> List<T> select(String sql, Object[] param, Class<T> clazz) {
        Connection connection = null;
        PreparedStatement ps = null;
        ResultSet rs  = null;
        List<T> list = null;

        try {
            connection = jdbcUtill.getConnection();
            ps = connection.prepareStatement(sql);
            //得到参数的个数
            ParameterMetaData pd = ps.getParameterMetaData();
            for (int i = 0;i<pd.getParameterCount();i++){
                ps.setObject(i+1,param[i]);
            }
            rs = ps.executeQuery();
            //获取结果集对象
            ResultSetMetaData rm = rs.getMetaData();
            while(rs.next()){
                //orm映射
                //通过反射实例化对象实体类对象
                T bean = clazz.getDeclaredConstructor().newInstance();
                //实体类的属性名必须要和表的列名相同
                for (int i = 0;i<rm.getColumnCount();i++){
                    //得到列名
                    String columnName = rm.getColumnName(i+1);
                    //获取列的值
                    Object value = rs.getObject(columnName);
                    //通过BeanUtill工具类讲解映射到对象中
                    BeanUtils.setProperty(bean,columnName,value);


                }
                list.add(bean);
            }

        }catch (Exception e){
            e.printStackTrace();
            throw new ApplicationException(e.getMessage());


        }finally {
            jdbcUtill.closeResource(rs, ps,connection);
        }

        return list;
    }


}

UsersService

public interface UsersService {

    Users findUsersById(int userid) throws ApplicationException;
    int modifyUsersById(Users users) ;
    List<Users> findUsersByLikeName(String username);



}

UsersServiceImpl

public  class UsersServiceimpl implements UsersService {

    @Override
    public Users findUsersById(int userid) throws ApplicationException {
        UsersDao ud  = new UsersDaoImpl();

        return ud.selectUsersById(userid);
    }

    @Override
    public int modifyUsersById(Users users) {
        UsersDao ud = new UsersDaoImpl();
        return ud.updateUsersById(users);
    }

    @Override
    public List<Users> findUsersByLikeName(String username) {
        UsersDao ud = new UsersDaoImpl();
        return ud.selectUsersByLikeName(username);

    }
}


Test3

public class Test3 {
    public static void main(String[] args) {
        UsersService us = new UsersServiceimpl();
        List<Users> list = us.findUsersByLikeName("a");
        for (Users users:list){
            System.out.println(users);
        }
    }
}

运行结果

java.lang.NullPointerException
	at cn.itbaizhan.dao.impl.BaseDaoImpl.select(BaseDaoImpl.java:88)
	at cn.itbaizhan.dao.impl.UsersDaoImpl.selectUsersByLikeName(UsersDaoImpl.java:71)
	at cn.itbaizhan.service.impl.UsersServiceimpl.findUsersByLikeName(UsersServiceimpl.java:29)
	at cn.itbaizhan.web.Test3.main(Test3.java:12)
Exception in thread "main" cn.itbaizhan.exception.ApplicationException
	at cn.itbaizhan.dao.impl.BaseDaoImpl.select(BaseDaoImpl.java:93)
	at cn.itbaizhan.dao.impl.UsersDaoImpl.selectUsersByLikeName(UsersDaoImpl.java:71)
	at cn.itbaizhan.service.impl.UsersServiceimpl.findUsersByLikeName(UsersServiceimpl.java:29)
	at cn.itbaizhan.web.Test3.main(Test3.java:12)


不知道哪错了,老师看一下

JAVA 全系列/第三阶段:数据库编程/JDBC技术 1684楼
JAVA 全系列/第三阶段:数据库编程/SQL 语言 1687楼

package com.itbaizhan;

import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Properties;

/**
 * 优化获取数据库连接
 */
public class JdbcTest2 {
    public static void main(String[] args) throws IOException, ClassNotFoundException, SQLException {

        //老规矩,工具类需要先实例化
        Properties properties=new Properties();

        //实例化结束,拿到输入流对象
        InputStream resourceAsStream = JdbcTest2.class.getClassLoader().getResourceAsStream("jdbc.properties");

        //拿到流对象,读取、并解析
        properties.load(resourceAsStream);


        //这块代码起的作用是什么?
        String url = properties.getProperty("url");            //获取数据库的url
        String name = properties.getProperty("username");      //获取数据库的用户名
        String pwd = properties.getProperty("pwd");            //获取数据库的密码
        String drivername = properties.getProperty("driver");     //获取数据库的驱动全名

        //加载注册驱动
        Class.forName(drivername);

        //通过驱动管理器获取  连接对象
        Connection connection = DriverManager.getConnection(url, name, drivername);
        System.out.println(connection);

    }
}
1、这一块代码存在的意义是什么?上面已经读取和解析了,下面也通过
管理器调用了里面的参数了呀?
2、这个错咋解决?


JAVA 全系列/第三阶段:数据库编程/JDBC技术 1688楼

package com.cx;

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

/**
 * 使用封装工具
 */
public class jdbcTest2 {
    //向Department表中添加一条数据
    public void insertDeparments(String department_name,int location_id){
        Connection conn = null;
        Statement state = null;
        try {
            //使用封装工具
            conn = jdbcUtil1.getConnection();

            String sql="insert into departments values(default,'"+department_name+"',"+location_id+")";
            state = conn.createStatement();   //通过conn对象调用Connection接口下createStatement方法
            int flag = state.executeUpdate(sql);
            System.out.println(flag);
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            jdbcUtil1.closeConnection(conn);
            jdbcUtil1.closeStatment(state);
        }
    }
    //更新departments表中的department_id为6的数据,将部门名称修改为教学不,location_id修改为6
    public  void  updateDepartments(String department_name,int location_id,int department_id){
        Connection conn = null;
        Statement state = null;
        try {
            conn= jdbcUtil1.getConnection();
            state = conn.createStatement();
            String sql = "update departments d set d.department_name = '"+department_name+"',d.location_id ="+location_id+" where d.department_id ="+department_id+"";
            int flag = state.executeUpdate(sql);
            System.out.println(flag);
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            jdbcUtil1.closeConnection(conn);
            jdbcUtil1.closeStatment(state);
        }
    }
    //查询Departments表中部门ID为6的部门信息
    public void selectDepartmentsById(int departmentId){
        Connection conn = null;
        Statement state = null;
        ResultSet rs = null;
        try {
            conn = jdbcUtil1.getConnection();
            state = conn.createStatement();
            String sql = "select * from departments d where d.department_id = "+departmentId;
            //执行查询返回结果
            rs = state.executeQuery(sql);
            while (rs.next()){
                int a = rs.getInt("department_id");
                String s = rs.getString("department_name");
                int b = rs.getInt(3);
                System.out.println(a+" "+s+" "+b);
            }
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            jdbcUtil1.closeConnection(conn);
            jdbcUtil1.closeStatment(state);
            jdbcUtil1.closeResultSet(rs);
        }
    }

    public static void main(String[] args) {
        jdbcTest2 test2 = new jdbcTest2();
        //test.insertDeparments("工程部",6);
       // test.updateDepartments("研发",6,8);
        test2.selectDepartmentsById(6);
    }
   
}
package com.cx;


import java.sql.*;
import java.util.ResourceBundle;

/**
 * 封装jdbc工具类
 */
public class jdbcUtil1 {
    private static String driver;
    private static String jdbcUrl;
    private static String username;
    private static String userpassword;
    static {
        ResourceBundle bundle = ResourceBundle.getBundle("jdbc");
        driver=bundle.getString("driver");
        jdbcUrl= bundle.getString("jdbcUrl");
        username=bundle.getString("username");
        userpassword=bundle.getString("userpassword");
        try {
            Class.forName(driver);
        }catch (Exception e){
            e.printStackTrace();
        }
    }
    //获取Connection对象
    public static Connection getConnection() {
        Connection conn = null;
        try {
            //获取连接
            conn = DriverManager.getConnection(jdbcUrl,username,userpassword);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return conn;
    }
    //关闭Statement
    public static void closeStatment(Statement state){
        try {
            if (state != null){
                state.close();
            }
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
    }
    //关闭Connection
    public static void closeConnection(Connection conn){
        try {
            if (conn != null){
                conn.close();
            }
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
    }
    //关闭
    public  static void closeResultSet(ResultSet rs){
        try {
            if (rs != null){
                rs.close();
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }
}
driver="com.mysql.jdbc.Driver"
jdbcUrl ="jdbc:mysql://localhost:3306/caixx?useUnicode=true&usecharacterEncoding=utf-8&useSSL=false"
username="root"
userpassword="root"


发现使用properties就会报错

image.png


不使用properties就正常, IDEA到底如何使用这个?

JAVA 全系列/第三阶段:数据库编程/JDBC技术(旧) 1689楼
JAVA 全系列/第三阶段:数据库编程/JDBC技术 1690楼
JAVA 全系列/第三阶段:数据库编程/Oracle 数据库的使用 1691楼
JAVA 全系列/第三阶段:数据库编程/SQL 语言 1692楼
JAVA 全系列/第三阶段:数据库编程/Oracle 数据库的使用 1693楼
JAVA 全系列/第三阶段:数据库编程/Oracle 数据库的使用 1695楼

课程分类

百战程序员微信公众号

百战程序员微信小程序

©2014-2025百战汇智(北京)科技有限公司 All Rights Reserved 北京亦庄经济开发区科创十四街 赛蒂国际工业园
网站维护:百战汇智(北京)科技有限公司
京公网安备 11011402011233号    京ICP备18060230号-3    营业执照    经营许可证:京B2-20212637