Java,插入sql写入sql文件里

本文介绍了如何使用Java编写一个程序,通过Map结构存储数据,然后将这些数据插入到SQL文件中,使用StringBuilder构建SQL语句并利用BufferedWriter进行文件操作。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Java,插入sql写入sql文件里

public static void main(String[] args) {
        // sql存放目录
        String sqlPath = "/sql/data.sql";
       
		Map<Integer, String> map = new HashMap<>();
		map.put(1, "11111111111");
      
        // 执行sql
        for(Map.Entry<Integer, String> entry : map.entrySet()){
            StringBuilder str = new StringBuilder();
            str.append("INSERT INTO `chapter`(`chapter_number`, `content_imges`) VALUES (");
            str.append(entry.getKey()+", ");
            str.append("'"+entry.getValue()+"');");
            // 写入sql文档
            appendSQLToFile(sqlPath, str.toString());
        }
    }



private static void appendSQLToFile(String filePath, String sqlStatement) {
        try (BufferedWriter writer = new BufferedWriter(new FileWriter(filePath, true))) {
        	// 换行
            writer.newLine();
            writer.write(sqlStatement);
            writer.newLine();
            System.out.println("SQL statement added to the file successfully.");
        } catch (IOException e) {
            System.err.println("Error occurred while writing to the file: " + e.getMessage());
        }
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值