Python & MySQL - Using Joins Example



Python uses c.execute(q) function to select a record(s) from a table where c is cursor and q is the select query to be executed.

Syntax

# execute SQL query using execute() method.
cursor.execute(sql)

result = cursor.fetchall()

for record in result:
   print(record)

Sr.No. Parameter & Description
1

$sql

Required - SQL query to select record(s) from a table.

First create a table in MySQL using following script and insert two records.

create table tcount_tbl(
   tutorial_author VARCHAR(40) NOT NULL,
   tutorial_count int
);

insert into tcount_tbl values('Julie', 2);
insert into tcount_tbl values('Robert', 1);

Example

Try the following example to get records from a two tables using Join. −

Copy and paste the following example as mysql_example.ty −

#!/usr/bin/python

import MySQLdb

# Open database connection
db = MySQLdb.connect("localhost","root","root@123", "TUTORIALS")

# prepare a cursor object using cursor() method
cursor = db.cursor()

sql = """SELECT a.tutorial_id, a.tutorial_author, b.tutorial_count
				FROM tutorials_tbl a, tcount_tbl b
				WHERE a.tutorial_author = b.tutorial_author"""

# execute SQL query using execute() method.
cursor.execute(sql)

# fetch all records from cursor
result = cursor.fetchall()

# iterate result and print records
for record in result:
  print(record)

# disconnect from server
db.close()

Output

Execute the mysql_example.py script using python and verify the output.

(1, 'Robert', 1)
(2, 'Julie', 2)
(3, 'Julie', 2)
Advertisements