Home php教程 PHP开发 Python operates mysql database

Python operates mysql database

Nov 23, 2016 am 11:31 AM
mysql python

Python’s standard database interface is Python DB-API, which provides developers with a database application programming interface.

Python database interface supports a lot of databases, you can choose the database that suits your project:

GadFly

mSQL

MySQL

PostgreSQL

Microsoft SQL Server 2000

Informix

Interbase

Oracle

Sybase

You can visit the Python database interface and API to view a detailed list of supported databases.

You need to download different DB API modules for different databases. For example, if you need to access Oracle database and Mysql data, you need to download Oracle and MySQL database modules.

DB-API is a specification. It defines a series of necessary objects and database access methods to provide consistent access interfaces for various underlying database systems and various database interface programs.

Python's DB-API implements interfaces for most databases. After using it to connect to each database, you can operate each database in the same way.

Python DB-API usage process:

Introduce API module.

Get the connection to the database.

Execute SQL statements and stored procedures.

Close the database connection.

What is MySQLdb?

MySQLdb is an interface for Python to connect to Mysql database. It implements the Python database API specification V2.0 and is based on the MySQL C API.

How to install MySQLdb?

In order to write MySQL scripts with DB-API, you must ensure that MySQL is installed. Copy the following code and execute it:

#!/usr/bin/python

import MySQLdb

If the output after execution is as shown below, it means you have not installed the MySQLdb module :

Traceback (most recent call last):

File "test.py", line 3, in

import MySQLdb

ImportError: No module named MySQLdb

To install MySQLdb, please visit http://sourceforge.net/projects/mysql-python. From here, you can choose the installation package suitable for your platform, which is divided into precompiled binary files and source code installation packages.

If you choose the binary file distribution version, the installation process can be completed with basic installation prompts. If you are installing from source code, you need to change to the top-level directory of the MySQLdb distribution and type the following command:

$ gunzip MySQL-python-1.2.2.tar.gz

$ tar -xvf MySQL -python-1.2.2.tar

$ cd MySQL-python-1.2.2

$ python setup.py build

$ python setup.py install

Note: Please make sure you have root permissions to Install the above modules.

Database connection

Before connecting to the database, please confirm the following:

You have created the database TESTDB.

In the TESTDB database, you have created the table EMPLOYEE

The EMPLOYEE table fields are FIRST_NAME, LAST_NAME, AGE, SEX and INCOME.

The user name used to connect to the database TESTDB is "testuser" and the password is "test123". You can set it yourself or directly use the root username and password. For Mysql database user authorization, please use the Grant command.

The Python MySQLdb module has been installed on your machine.

If you are not familiar with sql statements, you can visit our basic SQL tutorial

Example:

The following example links to Mysql's TESTDB database:

#!/usr/bin/python

import MySQLdb

# Open the database connection

db = MySQLdb.connect("localhost", "testuser", "test123", "TESTDB" )

# Use the cursor() method to get the operation cursor

cursor = db.cursor()

# Use the execute method to execute SQL statements

cursor.execute("SELECT VERSION()")

# Use the fetchone() method to obtain a database.

data = cursor.fetchone()

print "Database version: %s " % data

# Close the database connection

db.close()

Execute the above script The output is as follows :

Database version : 5.0.45

Create database table

If the database connection exists we can use the execute() method to create a table for the database, create table EMPLOYEE as follows:

#!/usr/bin/python

import MySQLdb

# Open database connection

db = MySQLdb.connect("localhost","testuser","test123","TESTDB")

# Use the cursor() method to get the operation cursor

cursor = db.cursor()

# If the data table already exists, use the execute() method to delete the table.

cursor.execute("DROP TABLE IF EXISTS EMPLOYEE")

#Create data table SQL statement

sql = """CREATE TABLE EMPLOYEE (

) FIRST_NAME CHAR(20) NOT NULL,

​​​​​LAST_NAME​CHAR(20 ),

AGE INT,

SEX CHAR(1),

INCOME FLOAT )"""

cursor.execute(sql)

#Close database connection

db.close()

Database insert operation

The following example uses the SQL INSERT statement to insert records into the table EMPLOYEE:

#!/usr/bin/python

import MySQLdb

#Open database connection

db = MySQLdb.connect("localhost","testuser","test123","TESTDB")

# Use the cursor() method to obtain the operation cursor

cursor = db.cursor()

# SQL INSERT statement

sql = """INSERT INTO EMPLOYEE(FIRST_NAME,

LAST_NAME, AGE, SEX, INCOME)

VALUES ('Mac', 'Mohan', 20, 'M', 200 0)"""

try:

​ #Execute sql statement

​ cursor.execute(sql)

​ #Submit to database for execution

​​ db.commit()

except:

​ # Rollback in case there is any error

db. rollback()

# Close the database connection

db.close()

The above example can also be written in the following form:

#!/usr/bin/python

import MySQLdb

# Open the database connection

db = MySQLdb.connect("localhost","testuser","test123","TESTDB" )

# Use the cursor() method to get the operation cursor

cursor = db.cursor()

#SQL insert statement

sql = "INSERT INTO EMPLOYEE(FIRST_NAME,

LAST_NAME, AGE, SEX, INCOME)

VALUES ( '%s', '%s', ' %d', '%c', '%d' )" %

('Mac', 'Mohan', 20, 'M', 2000)

try:

# Execute sql statement

cursor.execute (sql)

​ # Submit to the database for execution

​ db.commit()

except:

​ # Rollback when an error occurs

​ db.rollback()

# Close the database connection

db.close( )

Example:

The following code uses variables to pass parameters to the SQL statement:

...................... ............

user_id = "test123"

password = "password"

con.execute('insert into Login values("%s", "%s") ' %

                                                                                                                                                                             

Database query operation

Python queries Mysql using the fetchone() method to obtain a single piece of data, and the fetchall() method to obtain multiple pieces of data.

fetchone(): This method gets the next query result set. The result set is an object

fetchall(): receives all the returned result rows.

rowcount: This is a read-only property and returns the number of rows affected after executing the execute() method.

Example:

Query all data with a salary field greater than 1000 in the EMPLOYEE table:

#!/usr/bin/python

import MySQLdb

# Open the database connection

db = MySQLdb.connect("localhost","testuser","test123","TESTDB")

# Use the cursor() method to obtain the operation cursor

cursor = db.cursor()

# SQL query statement

sql = "SELECT * FROM EMPLOYEE

                                                                                                          using = cursor.fetchall()

for row in results:

[4]

​​​​​

                                                                                                                                                       print "Error: unable to fetch data"

# Close the database connection

db.close()

The above script execution results are as follows:

fname=Mac, lname=Mohan, age =20, sex=M, income=2000

Database update operation

The update operation is used to update the data in the data table. The following example changes all the SEX fields in the TESTDB table to 'M' and AGE fields. Increment by 1:

#!/usr/bin/python

import MySQLdb

# Open database connection

db = MySQLdb.connect("localhost","testuser","test123" , "TESTDB" )

# Use the cursor() method to obtain the operation cursor

cursor = db.cursor()

# SQL update statement

sql = "UPDATE EMPLOYEE SET AGE = AGE + 1

WHERE SEX = '%c'" % ('M')

try:

#Execute SQL statement

cursor.execute(sql)

#Submit to database for execution

db.commit()

except:

    # Rollback when an error occurs

db.rollback()

# Close the database connection

db.close()

Execute transactions

The transaction mechanism can ensure data consistency.

Transactions should have 4 attributes: atomicity, consistency, isolation, and durability. These four properties are often called ACID properties.

Atomicity. A transaction is an indivisible unit of work. All operations included in the transaction are either done or none.

Consistency. A transaction must change the database from one consistency state to another. Consistency and atomicity are closely related.

Isolation. The execution of a transaction cannot be interfered with by other transactions. That is, the operations and data used within a transaction are isolated from other concurrent transactions, and transactions executed concurrently cannot interfere with each other.

Durability. Continuity, also known as permanence, means that once a transaction is committed, its changes to the data in the database should be permanent. Subsequent operations or failures should not have any impact on it.

Python DB API 2.0 transactions provide two methods commit or rollback.

Example:

#SQL delete record statement

sql = "DELETE FROM EMPLOYEE WHERE AGE > '%d'" % (20)

try:

#Execute SQL statement

Cursor. execute(sql)

​ # Submit to the database

db.commit()

except:

In database programming, when a cursor is created, an invisible database transaction is automatically started.

The commit() method performs all update operations on the cursor, and the rollback() method rolls back all operations on the current cursor. Each method starts a new transaction.

Error handling

DB API defines some errors and exceptions for database operations. The following table lists these errors and exceptions:

Exception

Description

Warning is triggered when there is a serious warning, such as Inserted data is truncated and so on. Must be a subclass of StandardError.

Error All other error types except warnings. Must be a subclass of StandardError.

InterfaceError Triggered when an error occurs in the database interface module itself (not an error in the database). Must be a subclass of Error.

DatabaseError Triggered when an error related to the database occurs. Must be a subclass of Error.

DataError Triggered when an error occurs during data processing, such as division by zero error, data out of range, etc. Must be a subclass of DatabaseError.

OperationalError refers to errors that are not controlled by the user, but occur when operating the database. For example: the connection is unexpectedly disconnected, the database name is not found, transaction processing fails, memory allocation errors, etc. are errors that occur when operating the database. Must be a subclass of DatabaseError.

IntegrityError Errors related to integrity, such as foreign key check failure, etc. Must be a DatabaseError subclass.

InternalError Internal error of the database, such as cursor failure, transaction synchronization failure, etc. Must be a DatabaseError subclass.

ProgrammingError Programming error, such as the data table (table) is not found or already exists, SQL statement syntax error, wrong number of parameters, etc. Must be a subclass of DatabaseError.

NotSupportedError Not supported error refers to the use of functions or APIs that are not supported by the database. For example, the .rollback() function is used on the connection object, but the database does not support transactions or the transaction has been closed. Must be a subclass of DatabaseError.


Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1666
14
PHP Tutorial
1273
29
C# Tutorial
1253
24
MySQL and phpMyAdmin: Core Features and Functions MySQL and phpMyAdmin: Core Features and Functions Apr 22, 2025 am 12:12 AM

MySQL and phpMyAdmin are powerful database management tools. 1) MySQL is used to create databases and tables, and to execute DML and SQL queries. 2) phpMyAdmin provides an intuitive interface for database management, table structure management, data operations and user permission management.

Python vs. JavaScript: Development Environments and Tools Python vs. JavaScript: Development Environments and Tools Apr 26, 2025 am 12:09 AM

Both Python and JavaScript's choices in development environments are important. 1) Python's development environment includes PyCharm, JupyterNotebook and Anaconda, which are suitable for data science and rapid prototyping. 2) The development environment of JavaScript includes Node.js, VSCode and Webpack, which are suitable for front-end and back-end development. Choosing the right tools according to project needs can improve development efficiency and project success rate.

Golang vs. Python: The Pros and Cons Golang vs. Python: The Pros and Cons Apr 21, 2025 am 12:17 AM

Golangisidealforbuildingscalablesystemsduetoitsefficiencyandconcurrency,whilePythonexcelsinquickscriptinganddataanalysisduetoitssimplicityandvastecosystem.Golang'sdesignencouragesclean,readablecodeanditsgoroutinesenableefficientconcurrentoperations,t

Explain the purpose of foreign keys in MySQL. Explain the purpose of foreign keys in MySQL. Apr 25, 2025 am 12:17 AM

In MySQL, the function of foreign keys is to establish the relationship between tables and ensure the consistency and integrity of the data. Foreign keys maintain the effectiveness of data through reference integrity checks and cascading operations. Pay attention to performance optimization and avoid common errors when using them.

Laravel vs. Python (with Frameworks): A Comparative Analysis Laravel vs. Python (with Frameworks): A Comparative Analysis Apr 21, 2025 am 12:15 AM

Laravel is suitable for projects that teams are familiar with PHP and require rich features, while Python frameworks depend on project requirements. 1.Laravel provides elegant syntax and rich features, suitable for projects that require rapid development and flexibility. 2. Django is suitable for complex applications because of its "battery inclusion" concept. 3.Flask is suitable for fast prototypes and small projects, providing great flexibility.

Python vs. C  : Understanding the Key Differences Python vs. C : Understanding the Key Differences Apr 21, 2025 am 12:18 AM

Python and C each have their own advantages, and the choice should be based on project requirements. 1) Python is suitable for rapid development and data processing due to its concise syntax and dynamic typing. 2)C is suitable for high performance and system programming due to its static typing and manual memory management.

Compare and contrast MySQL and MariaDB. Compare and contrast MySQL and MariaDB. Apr 26, 2025 am 12:08 AM

The main difference between MySQL and MariaDB is performance, functionality and license: 1. MySQL is developed by Oracle, and MariaDB is its fork. 2. MariaDB may perform better in high load environments. 3.MariaDB provides more storage engines and functions. 4.MySQL adopts a dual license, and MariaDB is completely open source. The existing infrastructure, performance requirements, functional requirements and license costs should be taken into account when choosing.

SQL vs. MySQL: Clarifying the Relationship Between the Two SQL vs. MySQL: Clarifying the Relationship Between the Two Apr 24, 2025 am 12:02 AM

SQL is a standard language for managing relational databases, while MySQL is a database management system that uses SQL. SQL defines ways to interact with a database, including CRUD operations, while MySQL implements the SQL standard and provides additional features such as stored procedures and triggers.

See all articles