我提前为长代码道歉,但它可能是相关的。制作新代码进行演示也更容易。我可以使用 phpMyAdmin 删除表,运行这个脚本,然后返回到 phpMyAdmin 并看到它创建了表。但是,该表是空的,该脚本应该填充一个测试行。
import MySQLdb
def makeTable():
dbInfo = { 'username':'livetaor_atowrw', 'password':'~HIDDEN~', \
'server':'~HIDDEN~.com', 'base':'livetaor_towing', \
'table':'inventory' }
try:
sql = MySQLdb.connect(user=dbInfo['username'], \
passwd=dbInfo['password'], \
host=dbInfo['server'], db=dbInfo['base'])
cursor = sql.cursor ()
cursor.execute ("SELECT VERSION()")
cursor.execute ("""
CREATE TABLE inventory (
id INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
itemNumber VARCHAR(24),
itemDescription VARCHAR(255),
itemCategory VARCHAR(24),
itemVendor VARCHAR(48),
itemVendorItemNumber VARCHAR(24),
itemCost FLOAT,
itemMarkup FLOAT,
item4Customers BOOL,
itemOnReplenishment BOOL,
itemReplenishAlert INT,
itemBolivarQuantity INT,
itemLamarQuantity INT,
itemSpringfieldQuantity INT )
""")
cursor.execute ("""
INSERT INTO inventory (
itemNumber,
itemDescription,
itemCategory,
itemVendor,
itemVendorItemNumber,
itemCost,
itemMarkup,
item4Customers,
itemOnReplenishment,
itemReplenishAlert,
itemBolivarQuantity,
itemLamarQuantity,
itemSpringfieldQuantity,
) VALUES (
'TestItemNumber001',
'fictitious item description',
'TestCategory',
'Scripted Vendor',
'ITEM:maketable.py',
'1.00',
'1.33',
'1',
'1',
'6',
'65613',
'64759',
'65802'
)
""")
cursor.commit()
cursor.close()
sql.close()
except MySQLdb.Error, e:
error = "Error %d: %s" % (e.args[0], e.args[1])
confirm = None
confirm = raw_input('Do you know what you are doing? ')
if confirm == 'YeS':
makeTable()
else:
print "Didn't think so. Now, it's probably best to forget about this file."
最佳答案
关于您的代码有什么问题有一些猜测,但我将改为解决您隐含但未说出的问题。
那道题是这样写的:
My program runs, does not crash, and yet my table is empty. Why is that?
这是一个稍微不同的问题,它没有崩溃的原因是因为你明确告诉它不要:
看到这段代码了吗?
except MySQLdb.Error, e:
error = "Error %d: %s" % (e.args[0], e.args[1])
这会捕获您的异常,并将异常消息和其他位放入错误变量中。
但是,除非您检查该变量并根据其内容采取行动,否则您实际上是在吞下异常。
删除那个位并重新执行您的程序,您将找到程序失败的真正原因。
我个人认为这是您的 SQL 中的额外逗号,在此处列出所有列名之后:
itemLamarQuantity,
itemSpringfieldQuantity, <-- here
) VALUES (
'TestItemNumber001',
'fictitious item description',
关于python - MySQLdb 没有插入...我确实有 cursor.commit(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5614118/