python加mysql_python操作mysql

python操作mysql可用的第三方库有MySQLdb,pymysql等。

下面主要讲解MySQLdb:

1.用pip安装mysqlclient库,连接python和mysql

pip3 install mysqlclient

2.用python操作mysql

import MySQLdb

url = 'www.baidu.com'

content = 'this is content.'

conn = MySQLdb.connnect(host='localhost',user='root',passwd='root',db='scraping',charset='utf-8')

cur = conn.cursor()

cur.execute("insert into urls (url,content) values (%s,%s)",(url,content))

cur.close()

conn.commit()

conn.close()

#MySQLdb.connnect():用于连接数据库,

host:规定主机名或IP地址,

port:mysql服务器的端口号。

charset:设置编码格式

#conn.cursor():创建游标,通过游标可操作数据库方法执行sql语句。

3.查询数据库时获取返回值的函数fetchone()函数和fetchall()函数

fetchone()函数:返回值是单个元组,也就是一行记录,没有结果,则返回null.

fetchall()函数:返回值是二维元组,包含多个元组的一个元组,即返回多个行记录,没有结果,则返回().

fetchone()的使用:

cursor.execute(select username,password,nickname from user where id='%s'  %(input)

result=cursor.fetchone();

此时我们可以通过result[0],result[1],result[2]得到username,password,nickname

fetchall()的使用:

cursor.execute(select * from user)

result=cursor.fetchall();

此时select得到的可能是多行记录,那么我们通过fetchall得到的就是多行记录,是一个二维元组

((username1,password1,nickname1),(username2,password2,nickname2),(username3,password3,nickname))

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值