zoukankan      html  css  js  c++  java
  • Python操作MySQL数据库

    1. 安装mysql-python

    运行下面的命令:

    pip install mysql-python

    安装以后:

    import MySQLdb

    如果没有出错,就表明安装成功。

    2. 连接MySQL 

    db = MySQLdb.connect("localhost", "root", "1", "fs")

    其中localhost是服务器名,root是用户名,1是密码,fs是数据库名称,前提是MySQL数据库设置了相应的用户名和密码。

    连接成功以后,通过

    cur = db.cursor()

    获取游标。

    3. 查询数据

        cur.execute("select * from TableName where A = %s and B = %s order by C desc", (a, b))
        results = cur.fetchall()
        result = list(results)

    cur.execute()执行查询语句,cur.fetchal()取得结果集,再用list()把结果集转换成tuple数组,剩下的就很容易处理了。

    4. 写入数据

    cur.execute("insert into A values(%s, %s, %s, %s)", (x1, x2, x3, x4))
    db.commit()

    不论写入的字段在表中是什么类型,都使用%s,否则会出错,写完以后需要commit()。

    其他的还有Delete和Update操作,都是类似的,通过cur.execute()执行SQL语句,用%s代入参数就行了。

  • 相关阅读:
    Ajax原生XHR对象
    node-sass报错解决方法
    AngularJS中的表单验证
    javaScirpt事件详解-原生事件基础(一)
    jQuery Ajax总结
    Ruby 方法
    JS中常遇到的浏览器兼容问题和解决方法
    History对象
    转码与解码
    Location对象
  • 原文地址:https://www.cnblogs.com/mstk/p/8318726.html
Copyright © 2011-2022 走看看