zoukankan      html  css  js  c++  java
  • 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))

  • 相关阅读:
    BGP综合部署
    网络综合部署
    部署LNMP架构
    编译安装Nginx网站服务及优化
    Apache网页优化
    在windows上安装jupyter,配置单机版pyspark
    剑指offer54-字符流中第一个不重复的字符
    在centos001上安装jupyter,配置单机版pyspark
    剑指offer53-表示数值的字符串
    剑指offer50-数组中重复的数字
  • 原文地址:https://www.cnblogs.com/xl717/p/11612212.html
Copyright © 2011-2022 走看看