python 如何实现互动_如何与Python-Mysql互动

我已经完成了以下代码,我想请用户输入想要多少条新记录,然后再逐列填充这些记录。

import MySQLdb

import mysql.connector

mydb = mysql.connector.connect(

host="localhost",

user="root",

passwd="Adam!977",

database="testdb1"

)

cur = mydb.cursor()

get_tables_statement = """SHOW TABLES"""

cur.execute(get_tables_statement)

tables = cur.fetchall()

table = tables(gene)

x=input("How many records you desire: ")

x

print "Please enter the data you would like to insert into table %s" %(table)

columns = []

values = []

for j in xrange(0, len(gene)):

column = gene[j][0]

value = raw_input("Value to insert for column '%s'?"%(gene[j][0]))

columns.append(str(column))

values.append('"' + str(value) + '"')

columns = ','.join(columns)

values = ','.join(values)

print columns

print values

我得到的错误是关于表基因(该表存在于SQL的db中)回溯(最近一次调用是最近的):文件“ C:\ Users \ Admin \ Desktop \π.py”,第25行,在表= tables中(基因)NameError:未定义名称'基因'

另外,即使我也不知道代码是否正常工作。拜托,我需要帮助。谢谢

解决方案

python返回的错误归结于缺少变量的定义gene。在下面的行中,您引用gene,但不存在它:

table = tables(gene)

In the documentation for the python mysql connector, under cursor.fetchall() you'll notice that this method returns either a list of tuples or an empty list. It is therefore somewhat puzzling why you call tables as a function and attempt to pass a parameter to it - this is not correct syntax for accessing a list, or a tuple.

At the beginning of your code example you fetch a list of all of the tables in your database, despite knowing that you only want to update a specific table. It would make more sense to simply reference the name of the table in your SQL query, rather than querying all of the tables that exist and then in python selecting one. For example, the following query would give you 10 records from the table 'gene':

SELECT * FROM gene LIMIT 10

Below is an attempt to correct your code:

import mysql.connector

mydb = mysql.connector.connect(

host="localhost",

user="root",

passwd="Adam!977",

database="testdb1"

)

x=input("How many records you desire: ")

cur = mydb.cursor()

get_rows_statement = """SELECT * FROM gene"""

cur.execute(get_rows_statement)

results = cur.fetchall()

This should give you all of the rows within the table.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值