跟老齐学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官方文档的内容,把所有的参数都列出来,还有相关说明,请看官认真阅读。不过,上面几个是常用的,其它的看情况使用。

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



VS Code can run on Windows 8, but the experience may not be great. First make sure the system has been updated to the latest patch, then download the VS Code installation package that matches the system architecture and install it as prompted. After installation, be aware that some extensions may be incompatible with Windows 8 and need to look for alternative extensions or use newer Windows systems in a virtual machine. Install the necessary extensions to check whether they work properly. Although VS Code is feasible on Windows 8, it is recommended to upgrade to a newer Windows system for a better development experience and security.

In VS Code, you can run the program in the terminal through the following steps: Prepare the code and open the integrated terminal to ensure that the code directory is consistent with the terminal working directory. Select the run command according to the programming language (such as Python's python your_file_name.py) to check whether it runs successfully and resolve errors. Use the debugger to improve debugging efficiency.

VS Code can be used to write Python and provides many features that make it an ideal tool for developing Python applications. It allows users to: install Python extensions to get functions such as code completion, syntax highlighting, and debugging. Use the debugger to track code step by step, find and fix errors. Integrate Git for version control. Use code formatting tools to maintain code consistency. Use the Linting tool to spot potential problems ahead of time.

VS Code extensions pose malicious risks, such as hiding malicious code, exploiting vulnerabilities, and masturbating as legitimate extensions. Methods to identify malicious extensions include: checking publishers, reading comments, checking code, and installing with caution. Security measures also include: security awareness, good habits, regular updates and antivirus software.

Python excels in automation, scripting, and task management. 1) Automation: File backup is realized through standard libraries such as os and shutil. 2) Script writing: Use the psutil library to monitor system resources. 3) Task management: Use the schedule library to schedule tasks. Python's ease of use and rich library support makes it the preferred tool in these areas.

VS Code is the full name Visual Studio Code, which is a free and open source cross-platform code editor and development environment developed by Microsoft. It supports a wide range of programming languages and provides syntax highlighting, code automatic completion, code snippets and smart prompts to improve development efficiency. Through a rich extension ecosystem, users can add extensions to specific needs and languages, such as debuggers, code formatting tools, and Git integrations. VS Code also includes an intuitive debugger that helps quickly find and resolve bugs in your code.

Golang is more suitable for high concurrency tasks, while Python has more advantages in flexibility. 1.Golang efficiently handles concurrency through goroutine and channel. 2. Python relies on threading and asyncio, which is affected by GIL, but provides multiple concurrency methods. The choice should be based on specific needs.

VS Code not only can run Python, but also provides powerful functions, including: automatically identifying Python files after installing Python extensions, providing functions such as code completion, syntax highlighting, and debugging. Relying on the installed Python environment, extensions act as bridge connection editing and Python environment. The debugging functions include setting breakpoints, step-by-step debugging, viewing variable values, and improving debugging efficiency. The integrated terminal supports running complex commands such as unit testing and package management. Supports extended configuration and enhances features such as code formatting, analysis and version control.
