You are not logged in.

#1 2011-02-17 19:18:12

Krzesimir
Member
From: Wrocław
Registered: 2010-08-16
Posts: 7

MySQL + python

Hello.
I'm having problems with inserting data into tables using python.
For testing purposes I created table test with single column and inserted single value into it. Then I tried to insert something into it using this python code:

#! /usr/bin/python2

import MySQLdb

conn = MySQLdb.connect(***)
cur = conn.cursor()

print cur.execute("select * from test")
cur.execute("insert into test values(4)")
print cur.execute("select * from test")

cur.close()
conn.close()

conn = MySQLdb.connect(***)
cur = conn.cursor()
print cur.execute("select * from test")

cur.close()
conn.close()

IMHO the output should be: 1 2 2, but the output is: 1 2 1. So after I close connection inserted data seems to be removed.
I've got all required privileges.
Any ideas where the problem is?

Offline

#2 2011-02-17 19:32:02

EnvoyRising
Member
Registered: 2008-08-08
Posts: 118

Re: MySQL + python

IIRC, the API is transaction-based by default, so don't you need to commit changes? (eg conn.commit()). I'm just shooting from memory, so the syntax may be off

Last edited by EnvoyRising (2011-02-17 19:33:15)

Offline

#3 2011-02-17 20:02:01

firecat53
Member
From: Lake Stevens, WA, USA
Registered: 2007-05-14
Posts: 1,542
Website

Re: MySQL + python

Yes, you need the conn.commit(). Here's a generic sql_command I use to modularize that code:

def sql_statement(conn,statement):
    "abstracted sql command to include error checking"
    try:
        cursor = conn.cursor()
        cursor.execute(statement)
    except dbapi.Error, e:
        conn.rollback()
        raise Exception("Database Error %d: %s" % (e.args[0], e.args[1]))
    else:
        conn.commit()
        return cursor

Scott

Offline

#4 2011-02-17 20:44:03

Krzesimir
Member
From: Wrocław
Registered: 2010-08-16
Posts: 7

Re: MySQL + python

Thanks a lot. It's working of course.

Offline

#5 2011-02-17 21:23:04

firecat53
Member
From: Lake Stevens, WA, USA
Registered: 2007-05-14
Posts: 1,542
Website

Re: MySQL + python

Cool smile Don't forget to edit your first post and put [SOLVED] in the title.

Scott

Offline

Board footer

Powered by FluxBB