Home  >  Article  >  Backend Development  >  How to make a database connection? (Example analysis)

How to make a database connection? (Example analysis)

乌拉乌拉~
乌拉乌拉~Original
2018-08-22 17:19:171453browse

In this article, let’s learn about the relevant knowledge about python database connection. Some friends may have just come into contact with the python programming language and do not have a special understanding of this aspect. Next, this article will bring you knowledge about Database Connection.

Database connection

Understand the relevant matters that need to be determined before:

1. You have created the database TESTDB.

2 .In the TESTDB database you have created the table EMPLOYEE

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

4. 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. .

5. The Python MySQLdb module has been installed on your machine.

Database connection example display

The following example links to the TESTDB database of Mysql:

#!/usr/bin/python
# -*- coding: UTF-8 -*-
import MySQLdb
# 打开数据库连接
db = MySQLdb.connect("localhost", "testuser", "test123", "TESTDB", charset='utf8' )
# 使用cursor()方法获取操作游标 
cursor = db.cursor()
# 使用execute方法执行SQL语句
cursor.execute("SELECT VERSION()")
# 使用 fetchone() 方法获取一条数据
data = cursor.fetchone()
print "Database version : %s " % data
# 关闭数据库连接
db.close()

The results output by the above example As follows:

Database version : 5.0.45

The above is all the content of this article. This article mainly introduces the relevant knowledge of python database connection. I hope you can use the information to understand the above. content. I hope what I have described in this article will be helpful to you and make it easier for you to learn python.

For more related knowledge, please visit the Python tutorial column on the php Chinese website.

The above is the detailed content of How to make a database connection? (Example analysis). For more information, please follow other related articles on the PHP Chinese website!

Statement:
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