python 简单操作MySQL

前言

  1. python 配置 mysql
  2. 通过 python 爬取一些数据,存入数据库 并生成简单图表

环境
linux (Ubuntu)

安装
1-MySQL

$ sudo apt-get install mysql-server

2-MySQL-python

sudo apt-get install python-setuptools

sudo apt-get install libmysqld-dev

sudo apt-get install libmysqlclient-dev

sudo apt-get install python-dev

sudo easy_install mysql-python

安装成功之后,终端进入python,然后测试

1.png

测试数据库
Create a database name ‘book’ in your mysql

2.png
3.png

Connect to MySQL

4.png

Create table user

5.png

Insert record into your table user

6.png

Output the record from your table user

7.png

Run the program


8.png

小例子

import sys
import MySQLdb 
db = MySQLdb.connect(host='localhost',user='root',passwd='root',db='hello')
 
cursor = db.cursor()
 
cursor.execute("SELECT VERSION()")
 
data = cursor.fetchone()
 
# print "Database version : %s " % data
#---------------------------------------------------
# sql = "create table if not exists test2(name varchar(128) primary key, age int(4))"
# cursor.execute(sql)


sql = "insert into test2(name, age) values ('%s', %d)" % ("ccc", 21)
try:
    cursor.execute(sql)
except Exception, e:
    print e


db.commit()


sql = "select * from test2"
cursor.execute(sql)
alldata = cursor.fetchall()
if alldata:
    for rec in alldata:
        print rec[0], rec[1]
 
db.close()
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容