好得很程序员自学网

<tfoot draggable='sEl'></tfoot>

Mysql数据库安装和使用教程

在Python网络爬虫中,通常是通过TXT纯文本方式存储,其实也是可以存储在数据库中的;同时在WAMP(Windows、Apache、MySQL、PHP或Python)开发网站中,也可以通过Python构建网页的,所以这篇文章主要讲述Python调用MySQL数据库相关编程知识

Enter password: ******
mysql> show databases;
+--------------------+
| Database      |
+--------------------+
| information_schema |
| mysql       |
| performance_schema |
| test        |
| test01       |
+--------------------+
5 rows in set (0.00 sec)

mysql> use test01;
Database changed
mysql> show tables;
Empty set (0.00 sec)

mysql> create table student(username varchar(20),
  ->         password varchar(20),
  ->         stuid int primary key);
Query OK, 0 rows affected (0.33 sec)

mysql> show tables;
+------------------+
| Tables_in_test01 |
+------------------+
| student     |
+------------------+
1 row in set (0.00 sec)

mysql> desc student;
+----------+-------------+------+-----+---------+-------+
| Field  | Type    | Null | Key | Default | Extra |
+----------+-------------+------+-----+---------+-------+
| username | varchar(20) | YES |   | NULL  |    |
| password | varchar(20) | YES |   | NULL  |    |
| stuid  | int(11)   | NO  | PRI | NULL  |    |
+----------+-------------+------+-----+---------+-------+
3 rows in set (0.03 sec)

mysql> insert student(username, password, stuid)
  -> values('eastmount','123456',1)
  -> ;
Query OK, 1 row affected (0.05 sec)

mysql> select * from student;
+-----------+----------+-------+
| username | password | stuid |
+-----------+----------+-------+
| eastmount | 123456  |   1 |
+-----------+----------+-------+
1 row in set (0.00 sec)

mysql> update student set password='000000' where stuid='1';
Query OK, 1 row affected (0.10 sec)
Rows matched: 1 Changed: 1 Warnings: 0

mysql> select * from student;
+-----------+----------+-------+
| username | password | stuid |
+-----------+----------+-------+
| eastmount | 000000  |   1 |
+-----------+----------+-------+
1 row in set (0.00 sec)

mysql> delete from student where username='eastmount';
Query OK, 1 row affected (0.08 sec)

mysql> select * from student;
Empty set (0.00 sec)

mysql> 

三. Python调用MySQL基础知识

通常的安装方法是使用:pip install mysql 安装Python的MySQL库,但是总会报错。常见错误如:
Microsoft Visual C++ 9.0 is required (Unable to find vcvarsall.bat)
mysql.c(42) : fatal error C1083: Cannot open include file: 'config-win.h': No such file or directory
这些可能是驱动等问题。

正确安装方法:
建议下载一个MySQL-python-1.2.3.win-amd64-py2.7.exe文件进行安装。
官网地址:pypi.python.org/pypi/MySQL-python/
下载地址:www.gxlcms.com/softs/73369.html

下面我们要详细了解Python数据库API。从Python中访问数据库需要接口程序,接口程序是一个Python模块,它提供数据库客户端库(通常是C语言写成的)的接口供你访问。注意:Python接口程序都一定要遵守Python DB-API规范。
DB-API是一个规范。它定义了一系列必须的对象和数据库存取方式,以便为各种各样的底层数据库系统和多种多样的数据库接口程序提供一致的访问接口。DB-API为不同的数据库提供了一致的访问接口,在不同的数据库之间移植代码成为一件轻松的事情。

下面简单介绍DB-API的使用方法。

1.模块属性
DB-API规范里的以下特性和属性必须提供。一个DB-API兼容模块定义如下所示:

apilevel:模块兼容的DB-API版本号
threadsafety:线程安全级别
paramstyle:支持sql语句参数风格
connect():连接数据库 
user:Username
password:Password
host:Hostname
database:DatabaseName
dsn:Data source name 
import MySQLdb
conn = MySQLdb.connect(host='localhost', db='test01', user='root', passwd='123456', port=3306, charset='utf8') 
close():关闭数据库连接,或者关闭游标对象
commit():提交当前事务
rollback():取消当前事务
cursor():创建游标或类游标对象
errorhandler(cxn,errcls,errval):作为已给游标的句柄 
fetchone():可以看作fetch(取出) one(一个),也就是得到结果集的下一行(一行)。
fetchmany(size):可以看作fetch(取出)many(多个),这里的参数是界限,得到结果集的下几行(几行)
fetchall():顾名思义,取得所有。
execute(sql):执行数据库操作,参数为sql语句。
close():不需要游标时尽可能的关闭 
import MySQLdb
 
try:
  conn=MySQLdb.connect(host='localhost',user='root',passwd='123456',port=3306)
  cur=conn.cursor()
  res = cur.execute('show databases')
  print res
  for data in cur.fetchall():
    print '%s' % data
  cur.close()
  conn.close()
except MySQLdb.Error,e:
   print "Mysql Error %d: %s" % (e.args[0], e.args[1]) 
# coding:utf-8 
import MySQLdb
 
try:
  conn=MySQLdb.connect(host='localhost',user='root',passwd='123456',port=3306, db='test01', charset='utf8')
  cur=conn.cursor()
  res = cur.execute('select * from student')
  print u'表中包含',res,u'条数据\n'
  print u'数据如下:(姓名 密码 序号)'
  for data in cur.fetchall():
    print '%s %s %s' % data
  cur.close()
  conn.close()
except MySQLdb.Error,e:
   print "Mysql Error %d: %s" % (e.args[0], e.args[1]) 
# coding:utf-8 
import MySQLdb
 
try:
  conn=MySQLdb.connect(host='localhost',user='root',passwd='123456',port=3306, db='test01', charset='utf8')
  cur=conn.cursor()
  
  #查看表
  print u'插入前包含表:'
  cur.execute('show tables')
  for data in cur.fetchall():
    print '%s' % data

  #插入数据
  sql = '''create table teacher(id int not null primary key auto_increment,
                name char(30) not null,
                sex char(20) not null
     )'''
  cur.execute(sql)

  #查看表
  print u'\n插入后包含表:'
  cur.execute('show tables')
  for data in cur.fetchall():
    print '%s' % data
  cur.close()
  conn.commit()
  conn.close()
except MySQLdb.Error,e:
   print "Mysql Error %d: %s" % (e.args[0], e.args[1]) 
# coding:utf-8 
import MySQLdb
 
try:
  conn=MySQLdb.connect(host='localhost',user='root',passwd='123456',port=3306, db='test01')
  cur=conn.cursor()
  
  #插入数据
  sql = '''insert into student values(%s, %s, %s)'''
  cur.execute(sql, ('yxz','111111', '10'))

  #查看数据
  print u'\n插入数据:'
  cur.execute('select * from student')
  for data in cur.fetchall():
    print '%s %s %s' % data
  cur.close()
  conn.commit()
  conn.close()
except MySQLdb.Error,e:
   print "Mysql Error %d: %s" % (e.args[0], e.args[1]) 
>>> 
插入数据:
esatmount 123456 1
yangxiuzhang 123456 2
xiaoy 123456 3
yxz 111111 10
>>> 

同样,对数据库的增删改插都可以进行,请读者自行阅读。
推荐资料:python使用mysql数据库 - 虫师
后面我会结合Python爬虫讲述,如何将爬取的内容存储在数据库中,如我CSDN的博客,爬取博客标题、发布时间、阅读量和评论数。

MySQL数据库中结果如下图所示:

【相关推荐】

1. 特别推荐 :“php程序员工具箱”V0.1版本下载

2. Python免费视频教程

3. Python基础入门教程

以上就是Mysql数据库安装和使用教程的详细内容,更多请关注Gxl网其它相关文章!

查看更多关于Mysql数据库安装和使用教程的详细内容...

  阅读:50次