Python 操作数据库(3)

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/u010820857/article/details/86173969

通过python操作数据库的行为,任何对数据库进行的操作,都能够通过python-mysqldb来实现。

建立数据库

之前通过mysql>写SQL语句,建立了一个名字叫做mytest的数据库,然后用下面的方式跟这个数据库连接

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

在上面的连接中,参数db="mytest"其实可以省略,如果省略,就是没有跟任何具体的数据库连接,只是连接了mysql。

>>> import MySQLdb
>>> conn = MySQLdb.connect("localhost","root","123123",port=3306,charset="utf8")

这种连接没有指定具体数据库,接下来就可以用类似mysql>交互模式下的方式进行操作。

>>> conn.select_db("mytest")
>>> cur = conn.cursor()
>>> cur.execute("select * from users")
11L
>>> cur.fetchall()
((1L, u'hiekay', u'123123', u'[email protected]'), (2L, u'python', u'123456', u'[email protected]'), (3L, u'google', u'111222', u'[email protected]'), (4L, u'facebook', u'222333', u'[email protected]'), (5L, u'github', u'333444', u'[email protected]'), (6L, u'docker', u'444555', u'[email protected]'), (7L, u'\u5854', u'9988', u'[email protected]'), (8L, u'\u5854', u'9988', u'[email protected]'), (9L, u'\u5854', u'9988', u'[email protected]'), (10L, u'\u5854', u'9988', u'[email protected]'), (11L, u'\u5f20\u4e09', u'1122', u'[email protected]'))

conn.select_db()选择要操作的数据库,然后通过指针就可以操作这个数据库了。其它的操作跟之前的一样。

如果不选数据库,而是要新建一个数据库,如何操作?

>>> cur = conn.cursor()
>>> cur.execute("create database newtest")
1L

建立数据库之后,就可以选择这个数据库,然后在这个数据库中建立一个数据表。

>>> cur.execute("create table newusers (id int(2) primary key auto_increment, username varchar(20), age int(2), email text)")
0L

括号里面是引号,引号里面就是创建数据表的语句,一定是熟悉的。这样就在newtest这个数据库中创建了一个名为newusers的表

>>> cur.execute("show tables")
1L
>>> cur.fetchall()
((u'newusers',),)

这是查看表的方式。当然,可以在mysql>交互模式下查看是不是存在这个表。如下:

mysql> use newtest;
Reading table information for completion of table and column names
You can turn off this feature to get a quicker startup with -A

Database changed
mysql> show tables;
+-------------------+
| Tables_in_newtest |
+-------------------+
| newusers          |
+-------------------+
1 row in set (0.00 sec)

mysql> desc newusers;
+----------+-------------+------+-----+---------+----------------+
| Field    | Type        | Null | Key | Default | Extra          |
+----------+-------------+------+-----+---------+----------------+
| id       | int(2)      | NO   | PRI | NULL    | auto_increment |
| username | varchar(20) | YES  |     | NULL    |                |
| age      | int(2)      | YES  |     | NULL    |                |
| email    | text        | YES  |     | NULL    |                |
+----------+-------------+------+-----+---------+----------------+
4 rows in set (0.00 sec)

以上就通过python-mysqldb实现了对数据库和表的建立。

当然,能建就能删除。可以自行尝试,在这里就不赘述,原理就是在cur.execute()中写SQL语句。

关闭一切

当进行完有关数据操作之后,最后要做的就是关闭游标(指针)和连接。用如下命令实现:

>>> cur.close()
>>> conn.close()

注意关闭顺序,和打开的顺序相反。

关于乱码问题

这个问题是编写web时常常困扰程序员的问题,乱码的本质来自于编码格式的设置混乱。所以,要特别提醒诸位注意。在用python-mysqldb的时候,为了放置乱码,可以做如下统一设置:

  1. Python文件设置编码 utf-8(文件前面加上 #encoding=utf-8)
  2. MySQL数据库charset=utf8(数据库的设置方法,可以网上搜索)
  3. Python连接MySQL是加上参数 charset=utf8
  4. 设置Python的默认编码为 utf-8 (sys.setdefaultencoding(utf-8),这个后面会讲述)

代码示例:

#encoding=utf-8

import sys
import MySQLdb

reload(sys)
sys.setdefaultencoding('utf-8')

db=MySQLdb.connect(user='root',charset='utf8') 

MySQL的配置文件设置也必须配置成utf8 设置 MySQL 的 my.cnf 文件,在 [client]/[mysqld]部分都设置默认的字符集(通常在/etc/mysql/my.cnf):

[client] default-character-set = utf8
[mysqld] default-character-set = utf8

猜你喜欢

转载自blog.csdn.net/u010820857/article/details/86173969