Troubleshooting Python Code for Inserting into MySQL Database

MySQLpython

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.

Best Answer

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 :)

Related Question