簡體   English   中英

如何與 Python-Mysql 交互

[英]How to interact with 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 的數據庫中)回溯(最近一次調用最后一次):文件“C:\\Users\\Admin\\Desktop\\π.py”,第 25 行,表 = 表(基因)名稱錯誤:名稱“基因”未定義

另外,即使我不知道代碼是否正常工作。 請,我需要幫助。 謝謝

python 返回的錯誤歸結為缺少變量gene的定義。 在以下行中,您引用了gene ,但不存在它:

table = tables(gene)

在 python mysql 連接器的文檔中,在cursor.fetchall()您會注意到此方法返回元組列表或空列表。 因此,為什么將tables作為函數調用並嘗試向其傳遞參數有點令人費解 - 這不是訪問列表或元組的正確語法。

在代碼示例的開頭,您獲取了數據庫中所有表的列表,盡管您知道只想更新特定表。 在 SQL 查詢中簡單地引用表的名稱會更有意義,而不是查詢所有存在的表,然后在 python 中選擇一個。 例如,以下查詢將從表 'gene' 中獲取 10 條記錄:

SELECT * FROM gene LIMIT 10

以下是更正您的代碼的嘗試:

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()

這應該為您提供表中的所有行。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM