Learn › Class 12 › Computer Science / Informatics Practices › Python and MySQL connectivity
Python and MySQL connectivity
You will learn to
- Connect a Python program to a MySQL database
- Run queries and fetch results with a cursor
- Save changes with commit() and pass user input safely with placeholders
Helpful to know first: SQL commands; Python functions and exception handling.
The mysql.connector module lets Python talk to a MySQL server. Import it, then call mysql.connector.connect() with host, user, password and database.
con.is_connected() returns True when the link works. con.cursor() creates a cursor, which runs SQL with cursor.execute(query) and holds the results.
Fetching results
fetchone() returns the next row as a tuple, or None when no rows are left. fetchmany(n) returns up to n rows as a list. fetchall() returns all remaining rows. cursor.rowcount gives the number of rows affected or fetched so far.
INSERT, UPDATE and DELETE change data only after con.commit() is called. Close the cursor and the connection with close() when you are done.
Never join user input directly into an SQL string. A malicious value can change the query; this is called SQL injection. Use %s placeholders and pass the values as a tuple.
Common mix-ups
Not quite: After cursor.execute('INSERT ...'), the row is saved in the database.
Instead: The change is not permanent until con.commit() is called.
Not quite: Building a query with + and the user's input is fine for a school project.
Instead: It allows SQL injection. Always pass input through %s placeholders as a parameter tuple.