[零基础学python]经过Python链接数据库

用Python来编写网站,必需要可以经过python操做数据库,所谓操做数据库,就是经过python实现对数据的链接,以及对记录、字段的各类操做。上一讲提到的那种操做方式,是看官直接经过交互模式来操做数据库。html

安装python-MySQLdb

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

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

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

下载以后就能够安装了。shell

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

sudo apt-get install python-MySQLdb

在shell中输入上面的命令行,就安装了。看看,多么简洁的安装,请快快用ubuntu吧。我愿意作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官方文档的内容,把全部的参数都列出来,还有相关说明,请看官认真阅读。不过,上面几个是经常使用的,其它的看状况使用。

connect(parameters...)

Constructor for creating a connection to the database. Returns a Connection Object. Parameters are the same as for the MySQL C API. In addition, there are a few additional keywords that correspond to what you would pass mysql_options() before connecting. Note that some parameters must be specified as keyword arguments! The default value for each parameter is NULL or zero, as appropriate. Consult the MySQL documentation for more details. The important parameters are:

  • host: name of host to connect to. Default: use the local host via a UNIX socket (where applicable)
  • user: user to authenticate as. Default: current effective user.
  • passwd: password to authenticate with. Default: no password.
  • db: database to use. Default: no default database.
  • port: TCP port of MySQL server. Default: standard port (3306).
  • unix_socket: location of UNIX socket. Default: use default location or TCP for remote hosts.
  • conv: type conversion dictionary. Default: a copy of MySQLdb.converters.conversions
  • compress: Enable protocol compression. Default: no compression.
  • connect_timeout: Abort if connect is not completed within given number of seconds. Default: no timeout (?)
  • named_pipe: Use a named pipe (Windows). Default: don't.
  • init_command: Initial command to issue to server upon connection. Default: Nothing.
  • read_default_file: MySQL configuration file to read; see the MySQL documentation for mysql_options().
  • read_default_group: Default group to read; see the MySQL documentation for mysql_options().
  • cursorclass: cursor class that cursor() uses, unless overridden. Default: MySQLdb.cursors.Cursor. This must be a keyword parameter.
  • use_unicode: If True, CHAR and VARCHAR and TEXT columns are returned as Unicode strings, using the configured character set. It is best to set the default encoding in the server configuration, or client configuration (read with read_default_file). If you change the character set after connecting (MySQL-4.1 and later), you'll need to put the correct character set name in connection.charset.

If False, text-like columns are returned as normal strings, but you can always write Unicode strings.

This must be a keyword parameter.

  • charset: If present, the connection character set will be changed to this character set, if they are not equal. Support for changing the character set requires MySQL-4.1 and later server; if the server is too old, UnsupportedError will be raised. This option implies use_unicode=True, but you can override this with use_unicode=False, though you probably shouldn't.

If not present, the default character set is used.

This must be a keyword parameter.

  • sql_mode: If present, the session SQL mode will be set to the given string. For more information on sql_mode, see the MySQL documentation. Only available for 4.1 and newer servers.

If not present, the session SQL mode will be unchanged.

This must be a keyword parameter.

  • ssl: This parameter takes a dictionary or mapping, where the keys are parameter names used by the mysql_ssl_set MySQL C API call. If this is set, it initiates an SSL connection to the server; if there is no SSL support in the client, an exception is raised. This must be a keyword parameter.

我已经完成了数据库的链接,虽然是在交互模式下,看官你是否也实现了呢?下一讲,将开始讲述如何操做数据库。


《零基础学python》在线教程:www.itdiffer.com,这里按照章节排列好了,恭请各位光临,并不吝赐教。

相关文章
相关标签/搜索