pymysql使用python将随机数插入一列

时间:2016-08-10 04:18:14

标签: python mysql random pymysql

我想将随机数插入MySQL列rnd_value,其中包含100个随机数,包括1到100之间的使用python。

我将使用

从python生成随机数
random.randrange(1,100)

我已将MYSQL查询添加到数据库

 CREATE SCHEMA `random_values` ;
CREATE TABLE `exercise`.`random_values` (
  `id` INT NOT NULL AUTO_INCREMENT COMMENT '',
  `rnd_value` INT NULL COMMENT '',
  PRIMARY KEY (`id`)  COMMENT '');

我使用pymysql连接器将数据插入MySQL数据库。谁能建议我如何使用python将这些随机数插入MySQL列?

3 个答案:

答案 0 :(得分:3)

这个简单的方法怎么样?连接到db(假设localhost和数据库名称是练习)。然后将1个值逐个推到100?

import pymysql
import random

with pymysql.connect(host='localhost', db='exercise') as db:
   for i in random.randrange(1,100):
      qry = "INSERT INTO random_values (rnd_value) VALUES ({})".format(i)
      with db.cursor() as cur:
         cur.execute(qry)
         db.commit()

答案 1 :(得分:0)

从以下部分引用: Pymysql Insert Into not working

安装pymysql

pip install pymysql
在mysql中

CREATE TABLE `t1` (`c1` INT NULL,`c2` INT NULL )

python program

import pymysql
from random import randint
conn = pymysql.connect(host='localhost', port=3306, user="root")
cursor = conn.cursor()
for i in range (1, 101): # since you want to add 100 entries
  v1 = randint(1,100)
  v2 = randint(1,100)
  sql_statement = "INSERT INTO test.t1(c1, c2) VALUES (" + str(v1) + "," + str(v2)  + ")"
  cursor.execute(sql_statement)
conn.commit() # commit to insert records into database
cursor.close()
conn.close()
对于多个插入,使用某种循环机制,或使用多插入方法

然后切换到mysql控制台并激活select语句以查看插入是否成功

答案 2 :(得分:0)

感谢所有回复,这段代码似乎对我有用,

import pymysql
import random

connection=pymysql.connect(host='localhost',user='root',password='server',
                           db='exercise',charset='utf8mb4',
                             cursorclass=pymysql.cursors.DictCursor)


try:
    with connection.cursor() as cursor:
        for i in range (1, 101):
            j=random.randrange(1,100)
            sql = "INSERT INTO exercise.random_values(rnd_value) VALUES (%s)"
            cursor.execute(sql,(j))
            connection.commit()

finally:
    connection.close()