• python使用MySQLdb模块连接MySQL


    1.安装驱动

    目前有两个MySQL的驱动,我们可以选择其中一个进行安装:

    MySQL-python:是封装了MySQL C驱动的Python驱动;mysql-connector-python:是MySQL官方的纯Python驱动。

    MySQL-python:

    安装教程:http://www.cnblogs.com/jfl-xx/p/7299221.html

    mysql-connector-python:

    安装教程:http://www.cnblogs.com/Bgod/p/6995601.html

    2.测试连接

    这里使用MySQL-python驱动,即MySQLdb模块。

    test_connect.py

     1 #!/usr/bin/python
     2 # -*- coding: UTF-8 -*-
     3 
     4 import MySQLdb
     5 
     6 # 打开数据库连接
     7 db = MySQLdb.connect("localhost", "root", "123456", "test")
     8 
     9 # 使用cursor()方法获取操作游标
    10 cursor = db.cursor()
    11 
    12 # 使用execute方法执行SQL语句
    13 cursor.execute("SELECT VERSION()")
    14 
    15 # 使用 fetchone() 方法获取一条数据库。
    16 data = cursor.fetchone()
    17 
    18 print "Database version : %s " % data
    19 
    20 # 关闭数据库连接
    21 db.close()

    测试结果如下,连接成功:

    3.创建数据库表

    测试成功后,我们可以在python中直接为MySQL创建表:

    create_table.py

     1 #!/usr/bin/python
     2 # -*- coding: UTF-8 -*-
     3 
     4 import MySQLdb
     5 
     6 # 打开数据库连接
     7 db = MySQLdb.connect("localhost", "root", "123456", "test")
     8 
     9 # 使用cursor()方法获取操作游标
    10 cursor = db.cursor()
    11 
    12 # 如果数据表已经存在使用 execute() 方法删除表。
    13 cursor.execute("DROP TABLE IF EXISTS EMPLOYEE")
    14 
    15 # 创建数据表SQL语句
    16 sql = """CREATE TABLE EMPLOYEE (
    17          FIRST_NAME  CHAR(20) NOT NULL,
    18          LAST_NAME  CHAR(20),
    19          AGE INT,  
    20          SEX CHAR(1),
    21          INCOME FLOAT )"""
    22 
    23 cursor.execute(sql)
    24 
    25 # 关闭数据库连接
    26 db.close()

    建表结果 如下:

    4.操作数据库表

    注意点:MySQL中的占位符为%s

    operate_table.js

     1 #!/usr/bin/python
     2 # -*- coding: UTF-8 -*-
     3 
     4 import MySQLdb
     5 
     6 # 打开数据库连接
     7 db = MySQLdb.connect("localhost", "root", "123456", "test")
     8 
     9 # 使用cursor()方法获取操作游标
    10 cursor = db.cursor()
    11 
    12 # SQL插入语句
    13 ins_sql = """INSERT INTO EMPLOYEE(FIRST_NAME,
    14          LAST_NAME, AGE, SEX, INCOME)
    15          VALUES ('yu', 'jie', 20, 'M', 8000)"""
    16 
    17 ins_sql1 = 'insert into employee(first_name, last_name, age, sex, income) values (%s, %s, %s, %s, %s)'
    18 
    19 # SQL查询语句
    20 sel_sql = 'select * from employee where first_name = %s'
    21 
    22 # SQL更新语句
    23 upd_sql = 'update employee set age = %s where sex = %s'
    24 
    25 # SQL删除语句
    26 del_sql = 'delete from employee where first_name = %s'
    27 
    28 try:
    29     # 执行sql语句
    30     # insert
    31     cursor.execute(ins_sql)
    32     cursor.execute(ins_sql1, ('xu', 'f', 20, 'M', 8000))
    33     # select
    34     cursor.execute(sel_sql, ('yu',))
    35     values = cursor.fetchall()
    36     print values
    37     # update
    38     cursor.execute(upd_sql, (24, 'M',))
    39     # delete
    40     cursor.execute(del_sql, ('xu',))
    41 
    42     # 提交到数据库执行
    43     db.commit()
    44 except:
    45     # 发生错误时回滚
    46     db.rollback()
    47 
    48 # 关闭数据库连接
    49 db.close()

     执行插入操作

    执行查询操作

    执行更新操作

    执行删除操作

    查询语句的知识点:

    Python查询Mysql使用 fetchone() 方法获取单条数据, 使用fetchall() 方法获取多条数据。

    fetchone(): 该方法获取下一个查询结果集。结果集是一个对象

    fetchall():接收全部的返回结果行.

    例如该例子:

     1 sel_sql = 'select * from employee where first_name = %s'
     2 cursor.execute(sel_sql, ('yu',))
     3     results = cursor.fetchall()
     4     for row in results:
     5         fname = row[0]
     6         lname = row[1]
     7         age = row[2]
     8         sex = row[3]
     9         income = row[4]
    10         print "fname=%s, lname=%s,age=%d,sex=%s,income=%d" % (fname, lname, age, sex, income)

    结果如下:

  • 相关阅读:
    信号发生器的设计(期末课程设计)
    小程序异步获取openid解决方案
    微信小程序生成二维码之传参(接收的参数乱码该咋解决)
    小程序tabBar,点击进入tabBar刷新tabBar页面
    微信小程序函数执行顺序问题
    RESTful规范与常用状态码
    dedeCMS二次开发api简单接口代码
    DEDECMS怎么获取当前栏目及所有子栏目的文章数量
    DedeCMSV57数据库结构文档(数据字典)
    【JQuery插件】把网页或某div或table表格内容转为图片并下载
  • 原文地址:https://www.cnblogs.com/jfl-xx/p/7306081.html
Copyright © 2020-2023  润新知