简体   繁体   中英

Writing MySQL databases in Python using mySQLdb

So I have the following code, and it works:

for count in range(0,1000):
    L=[random.randint(0, 127),random.randint(0, 127),random.randint(0, 127)]
    random.randint(0, 127)
    name=''.join(map(chr,L))

    number=random.randint(0,1000)

    x.execute('insert into testTable set name=(%s), number=(%s)', (name, number))

Above, x is just the cursor I made (obviously). I just create a random string from ASCII values and a random number and write it to my database (this was a purely BS example so that I knew it worked)/

Then,

I have in another script:

x.execute('insert into rooms set \
        room_name=(%s),\
        room_sqft=(%s),\
        room_type=(%s),\
        room_purpose=(%s) ,\
        room_floor_number=(%s)',
        (name, sqft, roomType, room_use_ranking, floor))

And I get a syntax error: invalid syntax on the first line, right at the x. part of x.execute.

What is different between the two lines? In the problem code, all arguments but name are ints (name is a string) that are gotten from a int(raw_input(...)) type prompt that catches bad input errors.

Clearly this works, but what is going wrong in the second piece of code?

Thanks, nkk

There's a problem on the line BEFORE the x.execute. (x is unexpected at this point). Can you link more of the file?

Also, try this formatting, which can clear up this sort of thing by making the string one blob. (Your syntax highlighter should show it as one big multi-line string, too!)

sql = '''
    INSERT INTO rooms
    SET room_name=(%s),
        room_sqft=(%s),
        room_type=(%s),
        room_purpose=(%s),
        room_floor_number=(%s)
'''

x.execute(sql, (name, sqft, roomType, room_use_ranking, floor))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM