How to connect to the database in python

silencement
Release: 2019-06-13 17:43:04
Original
5601 people have browsed it

How to connect to the database in python

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

Python DB-API usage process:

Introduce API module

Get the connection to the database

Execute SQL statements and store Process

Close 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, built on 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
# -*- coding: UTF-8 -*-

import MySQLdb
Copy after login

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

Traceback (most recent call last):
  File "test.py", line 3, in <module>
    import MySQLdb
ImportError: No module named MySQLdb
Copy after login

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

EMPLOYEE table The 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.

Example:

The following example links to Mysql's TESTDB database:

#!/usr/bin/python
# -*- coding: UTF-8 -*-

import MySQLdb

# 打开数据库连接
db = MySQLdb.connect("localhost", "testuser", "test123", "TESTDB", charset=&#39;utf8&#39; )

# 使用cursor()方法获取操作游标 
cursor = db.cursor()

# 使用execute方法执行SQL语句
cursor.execute("SELECT VERSION()")

# 使用 fetchone() 方法获取一条数据
data = cursor.fetchone()

print "Database version : %s " % data

# 关闭数据库连接
db.close()
Copy after login

Execute the above code

Database version : 5.0.45
Copy after login

The above is the detailed content of How to connect to the database in python. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template