简体   繁体   中英

How do I sample a certain number of rows in a database table from a python script?

I have a table with a list of items. I created a randomly generated order list to create 500 orders with item range 1-5. I need to take the numbers in the orders list and randomly generate x amount of rows from the items table.

import random
import numpy

Orders = numpy.random.randint(1,6,size=500)

for o in Orders:
    cursor.execute("SELECT * FROM items limit 5")
    row = cursor.fetchmany(size = o)
    while row is not None:
        print(row)
        row = cursor.fetchmany(size = o)

this is giving me an endless amount of empty lists.

EDIT:

for o in Orders:
    cursor.execute("select * from items order by rand() limit 5")
    row = cursor.fetchmany(size = o)
    print(row)

I just edited the code to the above. It is now working for the first number in the order list. How do I get it to loop through the entire order list?

What is the intention of size = o ? Also, is that ao instead of 0? The size arg will limit the number of rows returned.

From the MySQL docs:

The number of rows returned can be specified using the size argument

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM