0

for now my code can print the list of the table, how to print spific column's data from MySQL by python

import mysql.connector

mydb = mysql.connector.connect(
  host="1xx.xxx.xxx.xxx",
  user="root", # defult user name is root
  password="password", 
  database="your_database",  
  auth_plugin='mysql_native_password' # In case plugging password is not working
)
                
mycursor = mydb.cursor()
mycursor.execute("SELECT * FROM your_database")                       
                                         
myresult = mycursor.fetchall()

for row in myresult:
  print("row_01 = ", row[0], )
  print("row_02 = ", row[1])
  print("row_03  = ", row[2])
  print("row_04  = ", row[3], "\n")
  • demo table in MySQL database

if I want to print out the content 4x3 only, how can I improve my code

+------+-------+------+------+
|row_01|row_02 |row_03|row_04|
+------+-------+------+------+
|  1x1 |  2x1  |  3x1 |  4x1 |
+------+-------+------+------+
|  1x2 |  2x2  |  3x2 |  4x2 |
+------+-------+------+------+
|  1x3 |  2x3  |  3x3 |  4x3 |
+------+-------+------+------+
|  1x4 |  2x4  |  3x4 |  4x4 |
+------+-------+------+------+
  • and my code result for now
row_01 =  1x1
row_02 =  2x1
row_03  =  3x1
row_04  =  4x1

row_01 =  1x2
row_02 =  2x2
row_03  =  3x2
row_04  =  4x2

row_01 =  1x3
row_02 =  2x3
row_03  =  3x3
row_04  =  4x3

row_01 =  1x4
row_02 =  2x4
row_03  =  3x4
row_04  =  4x4

is a dumb question, but how can I just get/print 4x3 or 1x1


ps. I did search relate discussion already, such as
MySQL: Get column name or alias from query
print table row mysql python

I just couldn't get it, Therfore, I ask here as my last step sor

  • 1
    If you only want one column, do `"SELECT col02 FROM table"`. You don't need to read everything from the database. – Tim Roberts Jan 09 '23 at 04:41

0 Answers0