【发布时间】:2013-04-07 15:35:34
【问题描述】:
我有以下代码:
### Write the new userid to the sql database
# Open database connection
db = MySQLdb.connect("sql01.domain1.lan","webuserid","test","webuserid" )
# prepare a cursor object using cursor() method
cursor = db.cursor()
dub_userid = int(userid)
# Check for dublicate of current userid value
sql = "SELECT * FROM webuserid WHERE userid = '"+str(dub_userid)+"'"
try:
# Execute the SQL command
cursor.execute(sql)
# Fetch all the rows in a list of lists.
results = cursor.fetchone()
data = cursor.fetchone()
except:
print "SQL Error: Unable to fetch data"
if data == None:
print "User doesn't exist - Creating"
else:
sys.exit("User exists")
# Prepare SQL query to INSERT a record into the database.
sql = """INSERT INTO webuserid(userid)
VALUES ('"""+userid+"""')"""
try:
# Execute the SQL command
cursor.execute(sql)
# Commit your changes in the database
db.commit()
except:
#Rollback in case there is any error
db.rollback()
# disconnect from server
db.close()
变量userid的字符串值为00001
我想要代码做的是连接到数据库(工作),将 userid 转换为 dub_userid 中的整数,并使用结果值查找重复项。
问题是,当我运行代码时,用户 ID 值为 00001 时会发生以下情况:
- 用户 ID 1 已提交到数据库(应该如此,因为没有其他名为 1 的用户 ID)
- 下一次运行,用户 ID 1 再次提交到数据库(不应该,因为用户 ID 1 已经存在)
- 第三次运行,脚本存在,并显示“用户存在”消息。
我已经尝试过使用数据和数据[1],但似乎无法找出问题所在。
【问题讨论】:
标签: python mysql python-2.7 constraints unique-constraint