爬虫再探之mysql简单使用

    在爬取数据量比较大时,用EXCEL存取就不太方便了,这里简单介绍一下python操作mysql数据库的一些操作。本人也是借助别人的博客学习的这些,但是找不到原来博客链接了,就把自己的笔记写在这里,这里感谢博文原创者。

    

import MySQLdb

# 打开数据库连接
mypwd = input("请输入数据库密码:") 
# 这里只是避免代码中直接出现自己的密码
# 下面中 “db” 是指定要使用的数据库,“charset” 是指定编码 db = MySQLdb.Connect(host="localhost", user="root", passwd=mypwd, db="test", use_unicode=True, charset="utf8")
# 获取操作游标 cursor = db.cursor() # 使用execute方法执行SQL语句 cursor.execute("SELECT VERSION()") # 使用fetchone 方法获取一条数据库 data = cursor.fetchone() print("Database's version is %s"%data)

#关闭数据库连接
db.close()

  输出结果如下图。

  上面算是一个基本流程吧。下面介绍一些具体的用法。

      关于数据表的创建:

import MySQLdb

#打开数据库链接
mypwd = input("请输入数据库密码:")
db = MySQLdb.Connect(host="localhost",user="root",passwd=mypwd,db="blog_test",use_unicode=True, charset="utf8")

cursor = db.cursor()

#如果数据已经存在,使用excute()方法删除表
cursor.execute("DROP TABLE IF EXISTS employee")

#创建数据表SQL语句,这里和mysql数据库的语法是一样的。
sql = """CREATE TABLE employee(
		first_name CHAR(20) NOT NULL,
		last_name CHAR(20),
		age INT,
		sex CHAR(1),
		income FLOAT )"""

cursor.execute(sql)

#关闭数据库连接
db.close()

  可以看到blog_test数据库中已经创建了表employee.

  关于数据的插入

import MySQLdb

mypwd = input("请输入数据库密码:")
db = MySQLdb.Connect(host="localhost", user="root", passwd=mypwd,db="blog_test",use_unicode=True,charset="utf8")

cursor = db.cursor()
sql = """INSERT INTO employee(first_name,last_name,age,sex,income)
		VALUES('Mac','Mohan',20,"M",2000)"""

try:
	cursor.execute(sql)
	#提交到数据库执行,这里切记要commit提交事务,否则无法完成保存。
	db.commit()
except:
	#Rollback in case there is any error
	db.rollback()

db.close()

  数据库输出如下。

  关于数据库的查询

import MySQLdb

mypwd = input("请输入数据库密码:")
db = MySQLdb.Connect(host="localhost", user="root", passwd=mypwd, db="blog_test", use_unicode=True, charset="utf8")
cursor = db.cursor()
sql = "SELECT * FROM employee"
try:
    cursor.execute(sql)
    results = cursor.fetchall()
    print(results)
    for row in results:
        fname = row[0]
        lname = row[1]
        age = row[2]
        sex = row[3]
        income = row[4]
        print("fname=%s,lname=%s,age=%d,sex=%s,income=%d"
            %(fname,lname,age, sex,income))
except:
    print("Error, unable to fetch data")

db.close()

  代码输出结果。

  至此python操作数据库的一些基本操作算是说完了。。。

原文地址:https://www.cnblogs.com/buzhizhitong/p/5657205.html