search
HomeBackend DevelopmentPython Tutorial跟老齐学Python之通过Python连接数据库

用Python来编写网站,必须要能够通过python操作数据库,所谓操作数据库,就是通过python实现对数据的连接,以及对记录、字段的各种操作。上一讲提到的那种操作方式,是看官直接通过交互模式来操作数据库。

安装python-MySQLdb

要想通过python来操作数据库,还需要在已经安装了mysql的基础上安装一个称之为mysqldb的库,它是一个接口程序,python通过它对mysql数据实现各种操作。

在编程中,会遇到很多类似的接口程序,通过接口程序对另外一个对象进行操作,比较简单。接口程序就好比钥匙,如果要开锁,人直接用手指去捅,肯定是不行的,那么必须借助工具,插入到锁孔中,把所打开,打开所之后,门开了,就可以操作门里面的东西了。那么打开所的工具就是接口程序。而打开所的工具会有便利与否之分,如果用这锁的钥匙,就便利,如果用别的工具,或许不便利(其实还分人,也就是人开锁的水平,如果是江洋大盗或者小毛贼什么的,擅长开锁,用别的工具也便利了),也就是接口程序不同,编码水平不同,都是考虑因素。

这里下载python-mysqldb:https://pypi.python.org/pypi/MySQL-python/

下载之后就可以安装了。

我这里只能演示ubuntu下安装的过程。

复制代码 代码如下:

sudo apt-get install python-MySQLdb

在shell中输入上面的命令行,就安装了。看看,多么简洁的安装,请快快用ubuntu吧。我愿意做ubuntu的免费代言。哈哈。

不管什么系统,安装不是难题。安装之后,怎么知道安装的结果呢?

复制代码 代码如下:

>>> import MySQLdb

在python的交互模式中,输入上面的指令,如果不报错,恭喜你,已经安装好了。如果报错,恭喜你,可以借着错误信息提高自己的计算机水平了,请求助于google大神。

交互模式下操作数据库之连接数据库

操作数据库的前提是先有数据库。

先建立一个数据库。

复制代码 代码如下:

qw@qw-Latitude-E4300:~$ mysql -u root -p
Enter password:  

打开数据库,正确输入密码之后,呈现下面的结果

复制代码 代码如下:

Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 373
Server version: 5.5.38-0ubuntu0.14.04.1 (Ubuntu)

Copyright (c) 2000, 2014, Oracle and/or its affiliates. All rights reserved.

Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

mysql>

在这个状态下,输入如下命令,建立一个数据库:

复制代码 代码如下:

mysql> create database qiwsirtest character set utf8;
Query OK, 1 row affected (0.00 sec)

注意上面的指令,如果仅仅输入:create database qiwsirtest,也可以,但是,我在后面增加了character set utf8,意思是所建立的数据库qiwsirtest,编码是utf-8的,这样存入汉字就不是乱码了。

看到那一行提示:Query OK, 1 row affected (0.00 sec),就说明这个数据库已经建立好了,名字叫做:qiwsirtest

数据库建立之后,就可以用python通过已经安装的mysqldb来连接这个名字叫做qiwsirtest的库了。进入到python交互模式(现在这个实验室做实验)。

复制代码 代码如下:

>>> import MySQLdb
>>> conn = MySQLdb.connect(host="localhost",user="root",passwd="123123",db="qiwsirtest",port=3306,charset="utf8")

逐个解释上述命令的含义:

host:等号的后面应该填写mysql数据库的地址,因为就数据库就在本机上(也称作本地),所以使用localhost,注意引号。如果在其它的服务器上,这里应该填写ip地址。一般中小型的网站,数据库和程序都是在同一台服务器(计算机)上,就使用localhost了。

user:登录数据库的用户名,这里一般填写"root",还是要注意引号。当然,如果是比较大型的服务,数据库会提供不同的用户,那时候可以更改为相应用户。但是,不同用户的权限可能不同,所以,在程序中,如果要操作数据库,还要注意所拥有的权限。在这里用root,就放心了,什么权限都有啦。不过,这样做,在大型系统中是应该避免的。

passwd:上述user账户对应的登录mysql的密码。我在上面的例子中用的密码是"123123"。不要忘记引号。

db:就是刚刚通create命令建立的数据库,我建立的数据库名字是"qiwsirtest",还是要注意引号。看官如果建立的数据库名字不是这个,就写自己所建数据库名字。

port:一般情况,mysql的默认端口是3306,当mysql被安装到服务器之后,为了能够允许网络访问,服务器(计算机)要提供一个访问端口给它。

charset:这个设置,在很多教程中都不写,结果在真正进行数据存储的时候,发现有乱码。这里我将qiwsirtest这个数据库的编码设置为utf-8格式,这样就允许存入汉字而无乱码了。注意,在mysql设置中,utf-8写成utf8,没有中间的横线。但是在python文件开头和其它地方设置编码格式的时候,要写成utf-8。切记!

注:connect中的host、user、passwd等可以不写,只有在写的时候按照host、user、passwd、db(可以不写)、port顺序写就可以,注意端口号port=3306还是不要省略的为好,如果没有db在port前面,直接写3306会报错.

其实,关于connect的参数还不少,下面摘抄来自mysqldb官方文档的内容,把所有的参数都列出来,还有相关说明,请看官认真阅读。不过,上面几个是常用的,其它的看情况使用。

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
Python vs. C  : Understanding the Key DifferencesPython vs. C : Understanding the Key DifferencesApr 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.

Python vs. C  : Which Language to Choose for Your Project?Python vs. C : Which Language to Choose for Your Project?Apr 21, 2025 am 12:17 AM

Choosing Python or C depends on project requirements: 1) If you need rapid development, data processing and prototype design, choose Python; 2) If you need high performance, low latency and close hardware control, choose C.

Reaching Your Python Goals: The Power of 2 Hours DailyReaching Your Python Goals: The Power of 2 Hours DailyApr 20, 2025 am 12:21 AM

By investing 2 hours of Python learning every day, you can effectively improve your programming skills. 1. Learn new knowledge: read documents or watch tutorials. 2. Practice: Write code and complete exercises. 3. Review: Consolidate the content you have learned. 4. Project practice: Apply what you have learned in actual projects. Such a structured learning plan can help you systematically master Python and achieve career goals.

Maximizing 2 Hours: Effective Python Learning StrategiesMaximizing 2 Hours: Effective Python Learning StrategiesApr 20, 2025 am 12:20 AM

Methods to learn Python efficiently within two hours include: 1. Review the basic knowledge and ensure that you are familiar with Python installation and basic syntax; 2. Understand the core concepts of Python, such as variables, lists, functions, etc.; 3. Master basic and advanced usage by using examples; 4. Learn common errors and debugging techniques; 5. Apply performance optimization and best practices, such as using list comprehensions and following the PEP8 style guide.

Choosing Between Python and C  : The Right Language for YouChoosing Between Python and C : The Right Language for YouApr 20, 2025 am 12:20 AM

Python is suitable for beginners and data science, and C is suitable for system programming and game development. 1. Python is simple and easy to use, suitable for data science and web development. 2.C provides high performance and control, suitable for game development and system programming. The choice should be based on project needs and personal interests.

Python vs. C  : A Comparative Analysis of Programming LanguagesPython vs. C : A Comparative Analysis of Programming LanguagesApr 20, 2025 am 12:14 AM

Python is more suitable for data science and rapid development, while C is more suitable for high performance and system programming. 1. Python syntax is concise and easy to learn, suitable for data processing and scientific computing. 2.C has complex syntax but excellent performance and is often used in game development and system programming.

2 Hours a Day: The Potential of Python Learning2 Hours a Day: The Potential of Python LearningApr 20, 2025 am 12:14 AM

It is feasible to invest two hours a day to learn Python. 1. Learn new knowledge: Learn new concepts in one hour, such as lists and dictionaries. 2. Practice and exercises: Use one hour to perform programming exercises, such as writing small programs. Through reasonable planning and perseverance, you can master the core concepts of Python in a short time.

Python vs. C  : Learning Curves and Ease of UsePython vs. C : Learning Curves and Ease of UseApr 19, 2025 am 12:20 AM

Python is easier to learn and use, while C is more powerful but complex. 1. Python syntax is concise and suitable for beginners. Dynamic typing and automatic memory management make it easy to use, but may cause runtime errors. 2.C provides low-level control and advanced features, suitable for high-performance applications, but has a high learning threshold and requires manual memory and type safety management.

See all articles

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 Tools

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment