0

This works in MySQL Workbench:

insert into nametest (name,surname) values('John''Krailling');

I am trying a get similar result with Pycharm with the following code:

import MySQLdb

db = MySQLdb.connect(host="localhost", # your host, usually localhost
                 user="root", # your username
                  passwd="iop", # your password
                  db="new_schema")# name of the data base
cur=db.cursor()

cur.execute("insert into nametest(name,surname) values('John', 'Green')")

The entry is added in Pycharm, but not in the table in the underlying database.

4
  • This: insert into nametest (name,surname) values('John''Krailling'); will fail - lack of comma between the two names. You are missing a semi-colon at the end of your Python statement. If that's not the issue, could it be failure to commit?
    – Vérace
    May 21, 2015 at 16:53
  • Verace, thanks for the answer. The semi-colon seems to make no difference. I thought commit is only needed in a transaction? May 21, 2015 at 20:06
  • Depending on the API transactions may or may not be explicit. I don't know what MySQLdb does behind the scenes - check the documentation. I have to learn Python shortly, so I'll be in your shoes pretty soon! :-)
    – Vérace
    May 21, 2015 at 21:43
  • Verace: db.commit was the answer! Nice weekend, May 22, 2015 at 15:48

1 Answer 1

0

ok this is my table: mysql> desc name_test; +-------+-------------+------+-----+---------+-------+ | Field | Type | Null | Key | Default | Extra | +-------+-------------+------+-----+---------+-------+ | fname | varchar(20) | NO | PRI | NULL | | | sname | varchar(20) | NO | | NULL | | +-------+-------------+------+-----+---------+-------+ 2 rows in set (0.00 sec)

and this is the code to insert the data:

    import mysql.connector

    db = mysql.connector.connect(host="127.0.0.1", # your host, usually localhost
             user="root", # your username
              passwd="", # your password
              db="music")# name of the data base
    cur=db.cursor()

    q = "insert into name_test(fname,sname) values(%s, %s)"
    v = { "bob", "smith" }

    cur.execute(q,v) #runs the query
    db.commit() #ensures that its saved
    cur.close() #closes the cursor
    db.close() #closes the connection

source: https://dev.mysql.com/doc/connector-python/en/connector-python-example-cursor-transaction.html

hope this helps :)

1
  • Thanks, Dan! that solved the problem. Nice weekend, Robert May 22, 2015 at 15:48

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.