python操作数据库

#!/usr/bin/python
#-*- coding:utf8 -*-

#主要演示python操作mysql数据库
#首先建立数据库
#数据库的基本操作就不说了
#create table Student
#(
#   number int primary key,
#   name char(10) not null,
#   age int,
#   sex char(1)
#)engine=innodb default charset=utf8;
#insert into Student values (1001,"Jack",22, 'M'),(1002,"Smith",23, 'M'),(1003, "Hellen",21,'F'),(1004, "John", 23,'M'),(1005,"Karen", 24, 'F');
#插入了5组数据
#select * from Student;
#+--------+--------+------+------+
#| number | name   | age  | sex  |
#+--------+--------+------+------+
#|   1001 | Jack   |   22 | M    |
#|   1002 | Smith  |   23 | M    |
#|   1003 | Hellen |   21 | F    |
#|   1004 | John   |   23 | M    |
#|   1005 | Karen  |   24 | F    |
#+--------+--------+------+------+

#现在进行代码的编写
import os, sys
import MySQLdb
try:
    conn = MySQLdb.connect(host='127.0.0.1', user='root',passwd='850528',db='test')
except Exception, e:
    print e
cursor=conn.cursor()
sql = "insert into Student values(%s, %s, %s, %s)"  #当成字符串对待
values = ('1006', "Bruce", '20', 'M')
try:
    cursor.execute(sql, values)
except Exception, e:
    print e

sql = 'select * from Student'
cursor.execute(sql)
data = cursor.fetchall()
if data:
    for arr in data:
        print arr[0],'---',arr[1],'---',arr[2],'---',arr[3]

sql='update Student set age=43 where number=1002'
cursor.execute(sql)
conn.commit()    #提交事务
cursor.close()
conn.close()



#然后,这个连接对象也提供了对事务操作的支持,标准的方法
#commit() 提交
#rollback() 回滚

#cursor用来执行命令的方法:
#callproc(self, procname, args):用来执行存储过程,接收的参数为存储过程名和参数列表,返回值为受影响的行数
#execute(self, query, args):执行单条sql语句,接收的参数为sql语句本身和使用的参数列表,返回值为受影响的行数
#executemany(self, query, args):执行单挑sql语句,但是重复执行参数列表里的参数,返回值为受影响的行数
#nextset(self):移动到下一个结果集

#cursor用来接收返回值的方法:
#fetchall(self):接收全部的返回结果行.
#fetchmany(self, size=None):接收size条返回结果行.如果size的值大于返回的结果行的数量,则会返回cursor.arraysize条数据.
#fetchone(self):返回一条结果行.

#scroll(self, value, mode='relative'):移动指针到某一行.如果mode='relative',则表示从当前所在行移动value条,如果 mode='absolute',则表示从结果集的第一行移动value条.


QQ交流群: 204944806

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值