python使用mysqldb连接数据库操作方法示例详解。最近用到了scrapy与mysql的交互,为了方便下次查看,总结了一下基本的操作,以备后续使用~
# -*- coding: utf-8 -*- #mysqldb import time, MySQLdb #连接 conn=MySQLdb.connect(host="localhost",user="root",passwd="",db="test",charset="utf8") cursor = conn.cursor() #写入 sql = "insert into user(name,created) values(%s,%s)" param = ("aaa",int(time.time())) n = cursor.execute(sql,param) print n #更新 sql = "update user set name=%s where id=3" param = ("bbb") n = cursor.execute(sql,param) print n #查询 n = cursor.execute("select * from user") for row in cursor.fetchall(): for r in row: print r #删除 sql = "delete from user where name=%s" param =("aaa") n = cursor.execute(sql,param) print n cursor.close() #关闭 conn.close()复制代码
其中,有几点需要注意:
1.数据库建立时即指定编码,可以防止后面插入中文时出现乱码;
2.数据库连接时参数chaset指定一下;
3.插入语句中的参数分开写;
4.对于中文的乱码问题,在插入数据库时若不进行utf-8转换,简历数据库表时字段为gb2312可避免乱码。