linux python 操作mysql_python 简单操作MySQL

前言

python 配置 mysql

通过 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,然后测试

41fc5440338d

1.png

测试数据库

Create a database name ‘book’ in your mysql

41fc5440338d

2.png

41fc5440338d

3.png

Connect to MySQL

41fc5440338d

4.png

Create table user

41fc5440338d

5.png

Insert record into your table user

41fc5440338d

6.png

Output the record from your table user

41fc5440338d

7.png

Run the program

41fc5440338d

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()

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值