2

I want to execute the sql_query given in below function and doing this way :

def get_globalid(self): 
    cursor = self.connect()
    sql_query = "REPLACE INTO globalid (stub) VALUES ('a'); SELECT LAST_INSERT_ID() as id"
    cursor = self.query(sql_query, cursor)
    for row in cursor:
        actionid = row[0]
    return actionid

connect() function I am using to make a connection and it is defined separately .The query function i am using above is to execute any query passed to it . It is defined as :

def query(self,query,cursor):
    cursor.execute(query)
    self.close()
    return cursor 

It is not working properly . Is there anything I am missing ? Is there any mysqli function for python like that in php (multi_query) ?

1
  • Try returning cursor.fetchall() in your query function. Also have you have written close explicitly? You can directly do cursor.close() to close the connection. Commented Nov 20, 2013 at 11:33

1 Answer 1

2

mysql-python can't execute semicolon separated multiple query statement. If you are looking for last_insert_id you can try with this:

conmy = MySQLdb.connect(host, user, passwd, db)
cursor = conmy.cursor()
sql_query = "REPLACE INTO globalid (stub) VALUES ('a')"
cursor.execute(sql)
last_insert_id = conmy.insert_id()
conmy.close()
Sign up to request clarification or add additional context in comments.

3 Comments

By this way how can I make sure that that I am getting that id which was generated after this insert(replace) only ? Can't that be a different id if lot of other things are calling this function only very frequently ?
connection.insert_id() get the ID from the last insert on that connection. if you call this method after the insert or replace you can be sure that the returned id is your last generated id.
You can also use last_insert_id = cursor.lastrowid aftet cursor.execute.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.