MySQLdb不插入...我确实有cursor.commit()
我提前为这段长代码道歉,不过这可能是有用的。其实用这段代码来演示比写新的代码要简单。我可以通过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."
3 个回答
0
这句话的意思是,是否不应该在光标上进行提交?
cursor.close()
sql.commit()
sql.close()
0
除非我真的是搞错了。
你插入的数据有13列,但只有12个值。
5
关于你代码的问题,有几种猜测,但我想先回答你隐含但没有说出来的问题。
这个问题可以理解为:
我的程序可以运行,没有崩溃,但我的表格是空的。这是为什么呢?
这个问题稍微有点不同,而它没有崩溃的原因是因为你明确告诉它不要崩溃:
看看这段代码:
except MySQLdb.Error, e:
error = "Error %d: %s" % (e.args[0], e.args[1])
这段代码会捕捉到你的异常,并把异常信息和其他一些内容放到一个错误变量里。
但是,除非你检查这个变量,并根据里面的内容采取行动,否则你实际上是在忽略这个异常。
把那部分去掉,然后重新运行你的程序,你就会发现程序失败的真正原因。
我个人猜测,可能是你在SQL语句中列出所有列名后面多了一个逗号,具体在这里:
itemLamarQuantity,
itemSpringfieldQuantity, <-- here
) VALUES (
'TestItemNumber001',
'fictitious item description',