windows 下载操作MYSQL实例 模块下载地址 http://sourceforge.net/projects/mysql-python/?source=typ_redirect
#取出数据库 10条数据
import MySQLdb
db = MySQLdb.connect("localhost","root","","tayirendb",charset="utf8" )
cursor = db.cursor()
sql = "select * from ta_member limit 10"
cursor.execute(sql)
results = cursor.fetchall()
print results
python 插入语句
#SQL语句里使用变量
sql = "INSERT INTO py_sina(title, url) VALUES ( '%s','%s')" % ( link.string, link['href'])
python 抓取新浪新闻 入库
# -*-coding:utf-8-*-
__author__ = 'Administrator'
from bs4 import BeautifulSoup
import urllib
import urllib2
import re
import MySQLdb
sina = 'http://wei.sohu.com/roll/'
request = urllib2.Request(sina)
response = urllib2.urlopen(request)
content = response.read()
soup = BeautifulSoup(content,'html.parser',from_encoding='utf-8')
links = soup.select('.f14list a')
# 打开数据库连接
db = MySQLdb.connect("localhost","root","","test",charset="utf8" )
# 使用cursor()方法获取操作游标
cursor = db.cursor()
cursor.execute('SET NAMES utf8')
for link in links:
sql = "INSERT INTO py_sina(title, url) VALUES ( '%s','%s')" % ( link.string, link['href'])
#value = {"title":link.string,"url":link['href']}
#cursor.execute(sql, value)
cursor.execute(sql)
db.commit()
print sql