爬虫学习 step_02 python连接MySQL

使用mysql-connector

pip install 来安装

pip install mysql-connector

说明:mysqldb与mysql-connector的区别
MySQLdb is a C module that links against the MySQL protocol implementation in the libmysqlclient library. It is faster, but requires the library in order to work.

mysql-connector is a Python module that reimplements the MySQL protocol in Python. It is slower, but does not require the C library and so is more portable.
简单的来说就是mysqldb需要mysql中C的编译环境

下面以mysql-connector为例

import mysql.connector

if __name__ == '__main__':
    db = mysql.connector.connect(user='root', password='数据库密码', database='数据库名称', charset='utf8')
    try:
        cursor = db.cursor()  #定义一个数据库游标
        sql = 'insert into question(title, content, user_id, created_date,comment_count) values("xxx", "xxx", 1, now(), 0)'  #定义一个插入sql语句,语法同sql
        cursor.execute(sql)  #执行这个语句
        qid = cursor.lastrowid  #取最新列的id
        print qid 

        sql = 'select * from question order by id desc limit 2' #查询语句
        cursor.execute(sql) 
        for each in cursor.fetchall():
                print each

        db.commit() #提交事务
    except Exception, e:
        print e.message
        db.rollback() #出现异常就数据回滚
    db.close #关闭数据库
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值