次のコードがあります。
### 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 です
コードで実行したいのは、データベースに接続し (動作)、ユーザー ID を dub_userid の整数に変換し、結果の値を使用して重複を探すことです。
問題は、コードを実行すると、userid 値が 00001 の場合に次のことが発生することです。
- ユーザー ID 1 はデータベースにコミットされます (1 と呼ばれる他のユーザー ID がないため、当然のことです)
- 次回の実行では、ユーザー ID 1 が再びデータベースにコミットされます (ユーザー ID 1 が既に存在するため、そうすべきではありません)。
- 3 回目の実行では、スクリプトが存在し、「ユーザーが存在します」というメッセージが表示されます。
data と data[1] の両方を試しましたが、何が問題なのかわかりません。