Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
882 views
in Technique[技术] by (71.8m points)

mysql - Python+MySQLdb weird problem

I have a problem using the MySQLdb library. I'm trying to insert values into my table but MySQL isn't showing them. What's more strange is the primary key is changing when I manually insert values using command prompt.

To show you an example:

'786', '2011-02-16 14:52:38', NULL
'787', '2011-02-16 14:52:52', NULL
'792', '2011-02-16 14:53:25', NULL

I manually insert some value at 786 and 787 (primary key), then I run my python script, stopping it after I got 4 values. I type in 'SELECT * from table' and I see no changes. Then I inset another value (manually) and it shows a new primary key '792'. It seems like the python script is deleting things...

Here's my python code:

try:
            conn = MySQLdb.connect(host = "127.0.0.1", 
                                   user = "root", 
                                   passwd = "eBao1234", 
                                   db = "test")
            cursor = conn.cursor()
            print 'data base connected'

            try:
                while 1:
                    localtime = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
                    i = i + 1



                    aRead = ser.readline()
                    aSplit = aRead.split(",")

                    if aSplit[0] == "t":


                        print str(i) + ", " + localtime +  ", " + aSplit[1]

                        tableName = "sampdb"
                        dbquery = "INSERT INTO %s (timestamp, tempReading) VALUES (NOW(), %s);" % (tableName, aSplit[1])
                        cursor.execute(dbquery)


            except KeyboardInterrupt:
                ser.close()
                #csvResults.close()
                #cursor.close()
                #conn.close()

                print "
Interrupted."
                raw_input("Press enter to exit.")

        except Exception,e:
            print str(e)
            print 'error connecting to database'
            cursor.close()
            conn.close()
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Turn on autocommit or commit your changes, see: My data disappeared!


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...