To write SQL queries in Python, you need to use a database module that provides a Python DBAPI-2.0-compliant interface to the database you want to interact with. Two widely-used modules include sqlite3
for SQLite databases and mysql-connector
for MySQL databases.
To connect to a database using sqlite3
, first import the module and then use the connect()
function to create a connection object. Supply the path to the SQLite database as an argument to connect()
:
main.py53 chars4 lines
To connect to a MySQL database using mysql-connector
, you need to first install the module:
main.py35 chars2 lines
Then import the module and use it to create a connection object. Supply the host, user, and password information as arguments to connect()
:
main.py157 chars9 lines
Once you've established a connection to your database, you can execute SQL queries using Python. To execute a query, use the execute()
method of your connection object and supply your SQL query as a string argument.
For example, to create a table named "students" with columns for "name", "age", and "grade" in SQLite:
main.py95 chars3 lines
And in MySQL:
main.py95 chars3 lines
To insert data into the table, you can use the execute()
method along with the SQL INSERT INTO
statement:
main.py243 chars8 lines
To retrieve data from a table, you can use the execute()
method along with the SQL SELECT
statement:
main.py208 chars8 lines
These examples demonstrate the basics of writing SQL queries in Python. Depending on your needs and your database, however, there are many more SQL operations and Python functions available to help you manipulate your data.
gistlibby LogSnag