image_pdfimage_print

Python conectando ao Mysql

import pymysql.cursors

# Conectando ao banco de dados
connection = pymysql.connect(host='', unix_socket='/tmp/mysql.sock',
                       user='', passwd='', db='')

try:
    with connection.cursor() as cursor:
        # Create a new record
        sql = "INSERT INTO tabela (col1, col2) VALUES ('var1', 'var2')"
        cursor.execute(sql)

    # connection is not autocommit by default. So you must commit to save
    # your changes.
    connection.commit()
finally:
    connection.close()

E para listar:


from __future__ import print_function

import pymysql

conn= pymysql.connect(host='', unix_socket='/tmp/mysql.sock',
                       user='', passwd='', db='')
cur = conn.cursor()

cur.execute("SELECT post_title, post_content FROM wp_posts LIMIT 0,10;")

print(cur.description)

print()

for row in cur:
    print(row)

cur.close()
conn.close()