简体   繁体   中英

Access specific table from MySQL database with Python

I have a MySQL database named my_database , and it that database there are a lot of tables. I want to connect MySQL with Python and to work with specific table named my_table from that database.

This is the code that I have for now:

import json
import pymysql

connection = pymysql.connect(user = "root", password = "", host = "127.0.0.1", port = "", database = "my_database")
cursor = connection.cursor()

print(cursor.execute("SELECT * FROM my_database.my_table"))

This code returns number of rows, but I want to get all columns and rows (all values from that table). I have also tried SELECT * FROM my_table but result is the same.

Did you read the documentation ? You need to fetch the results after executing: fetchone(), fetchall() or something like this:

import json
import pymysql

connection = pymysql.connect(user = "root", password = "", host = "127.0.0.1", port = "", database = "my_database")
with connection.cursor(pymysql.cursors.DictCursor) as cursor:
    cursor.execute("SELECT * FROM my_database.my_table")
    rows = cursor.fetchall()
    for row in rows:
        print(row)

You probably also want a DictCursor as the results are then parsed as dict.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM