首页 技术 正文
技术 2022年11月21日
0 收藏 721 点赞 4,500 浏览 1404 个字

Python Mysql 交互
A、Alex 的语法展示:

import MySQLdb try:     conn=MySQL.connect(host=’localhost’,user=’root’,passwod=’123qwe’,db=’test-DB’,port=’3306′)     cur =conn.cursor()     cur.execute(‘select * from user_info’)     cur.close()     conn.close()except MySQLdb.Errot,e:     print ‘Mysql Error  Msg:’ , e B、例子:例子1、获取数据

  1. # 打开数据库连接
  2. db = MySQLdb.connect("localhost","root","123qwe","host_list" )

  3. # 使用cursor()方法获取操作游标 
  4. cursor = db.cursor()
  5. # 使用execute方法执行SQL语句
  6. cursor.execute("SELECT VERSION()")
  7. # 使用 fetchone() 方法获取一条数据库。【以-行计数】
  8. data = cursor.fetchone()
  9. print "Database version : %s " % data
  10. # 关闭数据库连接
  11. db.close()

2、插去数据;
  1. # 创建数据表SQL语句

  2. sql = """CREATE TABLE EMPLOYEE (
    FIRST_NAME CHAR(20) NOT NULL,
    LAST_NAME CHAR(20),
    AGE INT,
    SEX CHAR(1),
    INCOME FLOAT )"""
  3. try:
  4. # 执行sql语句
  5. cursor.execute(sql)

  6. # 提交到数据库执行
  7. db.commit()
  8. except:
  9. # Rollback in case there is any error
  10. db.rollback()

常用函数:注意这个 commit( ) 提交               rollback( ) 回滚

(二)、插去多条数据。

  1. #!/usr/bin/python
  2. #coding:utf-8
  3. try:
  4. import MySQLdb
  5. db = MySQLdb.connect("localhost","root","123qwe","host_list" )
  6. cursor = db.cursor()
  7. v_list = []
  8. for i in range(10):
  9. v_list.append(("linux%s" %i,"moban%s" %i,"12%s" %i,"M", "2000"))
  10. print v_list
  11. cursor.executemany( "INSERT INTO EMPLOYEE \
  12. VALUES (%s, %s, %s, %s, %s)", v_list)
  13. cursor.close()
  14. db.commit()
  15. db.close()
  16. except MySQLdb.Error,e:
  17. print 'Mysql Error Msg:',e

执行结果:

查询数据库的结果:

例子展示:第一节、Alex 讲解 python+mysql 交互;
释义: cur.scroll(3,mode=”relative”)   #  光标相对的移动到 第三行; cur.scroll(0,mode=’absolute’)   print cur.fetchone ( )                #  取一行内容;从当前游标处。 print cur.fetchall( )                    #从当前位置取全部的行; ps: 默认的 是从 0行开始的,   
执行结果后:

来自为知笔记(Wiz)

下一篇: PHP 权限管理
相关推荐
python开发_常用的python模块及安装方法
adodb:我们领导推荐的数据库连接组件bsddb3:BerkeleyDB的连接组件Cheetah-1.0:我比较喜欢这个版本的cheeta…
日期:2022-11-24 点赞:878 阅读:8,906
Educational Codeforces Round 11 C. Hard Process 二分
C. Hard Process题目连接:http://www.codeforces.com/contest/660/problem/CDes…
日期:2022-11-24 点赞:807 阅读:5,430
下载Ubuntn 17.04 内核源代码
zengkefu@server1:/usr/src$ uname -aLinux server1 4.10.0-19-generic #21…
日期:2022-11-24 点赞:569 阅读:6,247
可用Active Desktop Calendar V7.86 注册码序列号
可用Active Desktop Calendar V7.86 注册码序列号Name: www.greendown.cn Code: &nb…
日期:2022-11-24 点赞:733 阅读:6,058
Android调用系统相机、自定义相机、处理大图片
Android调用系统相机和自定义相机实例本博文主要是介绍了android上使用相机进行拍照并显示的两种方式,并且由于涉及到要把拍到的照片显…
日期:2022-11-24 点赞:512 阅读:7,690
Struts的使用
一、Struts2的获取  Struts的官方网站为:http://struts.apache.org/  下载完Struts2的jar包,…
日期:2022-11-24 点赞:671 阅读:4,727