• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录

yxchun

  • 博客园
  • 联系
  • 订阅
  • 管理

公告

View Post

java JDBC 进行增删改查

1、读取配置文件中的参数

    private static String driver = ReadPropertiesUtils.getValue("jdbc.driver","data.properties");
    private static String url = ReadPropertiesUtils.getValue("jdbc.url","data.properties");
    private static String userName = ReadPropertiesUtils.getValue("jdbc.userName","data.properties");
    private static String password = ReadPropertiesUtils.getValue("jdbc.password","data.properties");
//创建的数据库连接
private static Connection conn = null;
ReadPropertiesUtils.class
package inter7.utils;

import org.springframework.core.io.support.PropertiesLoaderUtils;

import java.util.Enumeration;
import java.util.HashMap;
import java.util.Properties;

/**
 * @Auther: yxchun
 * @Date: 2022/5/22 - 18:20
 * @Description:inter403.utils
 * @Version:1.0
 */
public class ReadPropertiesUtils {

    private static HashMap<String, String> propertiesMap = new HashMap<String, String>();


    private static void loadlProperty(Properties props) {
        @SuppressWarnings("rawtypes")
        Enumeration en = props.propertyNames();
        while (en.hasMoreElements()) {
            String key = (String) en.nextElement();
            String value = props.getProperty(key);
            propertiesMap.put(key, value);
        }
    }

    public static String getValue(String key, String fileName) {
        Properties prop = null;
        try {
            // 通过Spring中的PropertiesLoaderUtils工具类进行获取
            prop = PropertiesLoaderUtils.loadAllProperties(fileName);
            loadlProperty(prop);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return propertiesMap.get(key);
    }

    public static void main(String[] args) {
System.out.println(getValue("rechargeFilePath","filePath.properties"));
    }
}
View Code

 

data.properties

jdbc.driver=com.mysql.cj.jdbc.Driver
jdbc.url=jdbc:mysql://127.0.0.1:3306/testspringboot?allowPublicKeyRetrieval=true&useSSL=false
jdbc.userName=root
jdbc.password=root

2、获取数据库连接

    public static Connection getConnection() throws SQLException {

        try {
            Class.forName(driver);
            conn = DriverManager.getConnection(url, userName, password);
            System.out.println("register driver success");
            if (conn == null) {
                System.out.println("conn == null");
            }
            return conn;
        } catch (ClassNotFoundException e) {

            System.out.println("register driver failed");
            e.printStackTrace();
            return null;
        }

3、查询,查询结果返回Lis<T>

  /**
     * 返回多条记录
     */
    public static <T> List<T> selectParam(Class<T> tClass, String sql, Object... args) {
        ResultSet rs = null;
        PreparedStatement ps = null;
        //创建集合对象
        ArrayList<T> list = new ArrayList<>();
        try {

            ps = getConnection().prepareStatement(sql);
            for (int i = 0; i < args.length; i++) {
                ps.setObject(i+1,args[i]);
            }
            //执行获取结果集
            rs = ps.executeQuery();
            ResultSetMetaData rsmd = rs.getMetaData();
            //获取列数
            int columnCount = rsmd.getColumnCount();
            while (rs.next()) {
                T t = tClass.newInstance();
                for (int i = 0; i < columnCount; i++) {
                    //获取列值
                    Object columnValue = rs.getObject(i + 1);
                    //获取列的别名
                    String columnLable = rsmd.getColumnLabel(i + 1);

                    //利用反射为每一个对象进行赋值操作赋值
                    Field field = tClass.getDeclaredField(columnLable);
                    field.setAccessible(true);
                    field.set(t, columnValue);
                }
                list.add(t);
            }
            return list;
        } catch (Exception e) {
            System.out.println(e.getMessage());
        } finally {
            try {
                closeResoure(conn, ps, rs);
            } catch (Exception e) {
                System.out.println(e.getMessage());
            }
        }
        return null;
    }

4、修改、新增、删除 ,返回执行结果

    public static boolean updatePOJO(String sql) throws SQLException {
        PreparedStatement stat = getConnection().prepareStatement(sql);
        int i = stat.executeUpdate();
        closeResoure(conn,stat);
        if(i==1){
            return true;
        }else{
            return false;
        }


    }

5、关闭资源

    /**
     * 关闭资源
     */
    public static void closeResoure(Connection conn, PreparedStatement ps) {
        try {
            if (ps != null) {
                ps.close();
            }
        } catch (SQLException throwables) {
            //
            throwables.printStackTrace();
        }
        try {
            if (conn != null) {
                conn.close();
            }
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
    }

    /**
     * 重载一下关闭流,方便查询操作时使用
     */
    public static void closeResoure(Connection conn, PreparedStatement ps, ResultSet rs) {
        try {
            if (ps != null) {
                ps.close();
            }
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        try {
            if (conn != null) {
                conn.close();
            }
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        try {
            if (rs != null) {
                rs.close();
            }
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
    }
View Code

6、测试增删改查

    public static void main(String[] args) throws SQLException {
        //测试查询,封装后查询将会根据别名
//        String sql = "select uid as uid,nick as nick from j_user where crtime like ?";
//        List<JUser> list = selectParam(JUser.class,sql, "2019-12%%");
//        System.out.println("in main() \t list="+list.size());
//        for (JUser user:list){
//            System.out.println(user.getUid()+"\t"+user.getNick());
//        }

        //测试update
//        String sql="update j_user set nick='我是张三2' where uid='123@qq.com'";


        //测试add
        String sql="INSERT INTO `j_user`(`id`, `uid`, `password`, `nick`, `img`, `signin`, `signinTime`, `age`, `sex`, `info`, `state`, `crtime`, `uptime`) VALUES ('17bd294a109b48afb4f6024842332c47', '123@qq.com', '202cb962ac59075b964b07152d234b70', 'yangchun', '20191204100400.jpeg', 1, '2019-11-24 20:07:49', 18, 1, NULL, 3, '2019-11-24 20:04:48', '2019-11-24 20:04:48');";
        //测试delete
//        String sql="delete from j_user where uid='123@qq.com'";

        System.out.println(updatePOJO(sql));

    }

posted on 2022-07-30 14:58  yxchun  阅读(598)  评论(0)    收藏  举报

刷新页面返回顶部
 
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3