本文介绍了Django:使用自定义的原始SQL插入与执行和MySQL的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要将大量数据上传到MySQL数据库。对于大多数型号,我使用django的ORM,但我的一个模型将有数十亿(!)个实例,我想优化其插入操作。



我不能似乎找到一种方法来使executemany()工作,而在googling之后似乎几乎没有任何例子。



我正在寻找正确的sql语法+正确的命令语法+正确的值数据结构支持以下sql语句的executemany命令:

  INSERT INTO`some_table`(` int_column1`,`float_column2`,`string_column3`,`datetime_column4`)VALUES(%d,%f,%s,%s)

是的,我明确声明了id(int_column1)的效率。



一个简单的示例代码将是非常好的

解决方案

这里是一个实际使用executemany()的解决方案!



例如将工作。



但请注意,在Django中,您需要使用%s占位符而不是问号。



此外,您将需要管理您的交易。我不会进入这里,因为有很多文件可用。

 从django.db导入连接,事务
cursor = connection.cursor()



query ='''INSERT INTO table_name
(var1,var2,var3)
VALUES %s,%s,%s)'''


queryList = buildQueryList()

#here buildQueryList()表示一些函数来填充
#列表中有多个记录
#在元组格式(value1,value2,value3)中。


cursor.executemany(query,queryList)

transaction.commit()


I need to upload a lot of data to a MySQL db. For most models I use django's ORM, but one of my models will have billions (!) of instances and I would like to optimize its insert operation.

I can't seem to find a way to make executemany() work, and after googling it seems there are almost no examples out there.

I'm looking for the correct sql syntax + correct command syntax + correct values data structure to support an executemany command for the following sql statement:

INSERT INTO `some_table` (`int_column1`, `float_column2`, `string_column3`, `datetime_column4`) VALUES (%d, %f, %s, %s)

Yes, I'm explicitly stating the id (int_column1) for efficiency.

A short example code would be great

解决方案

Here's a solution that actually uses executemany() !

Basically the idea in the example here will work.

But note that in Django, you need to use the %s placeholder rather than the question mark.

Also, you will want to manage your transactions. I'll not get into that here as there is plenty of documentation available.

from django.db import connection,transaction
cursor = connection.cursor()



query=''' INSERT INTO table_name 
        (var1,var2,var3) 
        VALUES (%s,%s,%s) '''


queryList=buildQueryList() 

#here buildQueryList() represents some function to populate
#the list with multiple records
#in the tuple format (value1,value2,value3).


cursor.executemany(query,queryList)

transaction.commit()

这篇关于Django:使用自定义的原始SQL插入与执行和MySQL的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-31 12:38