java 怎么多表同时插入到数据库啊?
PHP中文网
PHP中文网 2017-04-18 10:35:54
0
4
475
PHP中文网
PHP中文网

认证0级讲师

全部回复(4)
大家讲道理

JDBC本身支持批量更新,具体API如下:

addBatch(String sql):Statement类的方法, 可以将多条sql语句添加Statement对象的SQL语句列表中
addBatch():PreparedStatement类的方法,可以将多条预编译的sql语句添加到PreparedStatement对象的SQL语句列表中
executeBatch():把Statement对象或PreparedStatement对象语句列表中的所有SQL语句发送给数据库进行处理
clearBatch():清空当前SQL语句列表

使用批量更新API,我将你的代码调整如下:(注:如果SQL列表包含过多的待处理SQL语句, 可能会产生OutOfMemory错误。所以需要及时处理SQL语句列表。)

public class AddBatchSql {

    public void add(String fid,String title,String content){
        Connection connection = null;
        Statement stmt = null;
        String sql1 = null;
        String sql2 = null;

        try{
            connection = ConnectionUtils.getConnection();
            stmt = connection.createStatement();
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String dateValue = simpleDateFormat.format(new Date());
            sql1 = "insert into news_base(fid,title,date,author) values("+fid+",'"+title+"','"+dateValue+"','Admin')";
            sql2 = "insert into news_content (cid,content) values("+fid+",'"+content+"')";
            List<String> sqlList = new ArrayList<String>();
            sqlList.add(sql1);
            sqlList.add(sql2);
            for (int i = 0; i < sqlList.size(); i++) {
                String sql = sqlList.get(i);
                stmt.addBatch(sql);
                if (i==500) {
                    stmt.executeBatch();//为避免出现OutOfMemory错误,及时处理
                    stmt.clearBatch();//清空列表
                }
            }
            //最后一次列表不足500条,处理
            stmt.executeBatch();
        }catch(Exception e){
            e.printStackTrace();
        }finally{
            if(stmt != null){
                try{
                    stmt.close();
                }catch(Exception e){
                    e.printStackTrace();
                }
            }
        }
    }
    
}
伊谢尔伦

多条相关联的记录用这种方法肯定是要一行一行写的,你可以自己封装一下,看起来应该好不了多少,还是用的orm框架吧,可读性好些。

伊谢尔伦

可以用addBatch()批量处理语句

小葫芦

框架的好处就体现出来了,会帮你做重复的操作

热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责声明 Sitemap
PHP中文网:公益在线PHP培训,帮助PHP学习者快速成长!