Overview:
-
Primary key of a MySQL table can be retrieved using the SQL statement show keys or by querying the database information_schema.
-
Note that the primary key of a table is a clustered index. Hence the SQL statements show keys or show index can be used to get this information.
Example:
# Example Python program that gets the primary key column name(s) import pymysql # Connect with the DB Server tableName = "test.usr_login" connectionInstance = pymysql.connect(host=ip2Connect, user=dbUsr, password=dbUsrPwd, try: # SQL Show statement to get primary key # Execute the SHOW keys statement # Fetch all the rows for primaryKey in primaryKeys: except Exception as e: finally: |
Output:
{'Table': 'usr_login', 'Non_unique': 0, 'Key_name': 'PRIMARY', 'Seq_in_index': 1, 'Column_name': 'usr', 'Collation': 'A', 'Cardinality': 0, 'Sub_part': None, 'Packed': None, 'Null': '', 'Index_type': 'BTREE', 'Comment': '', 'Index_comment': ''} {'Table': 'usr_login', 'Non_unique': 0, 'Key_name': 'PRIMARY', 'Seq_in_index': 2, 'Column_name': 'ts', 'Collation': 'A', 'Cardinality': 0, 'Sub_part': None, 'Packed': None, 'Null': '', 'Index_type': 'BTREE', 'Comment': '', 'Index_comment': ''} |