python Mysql for 2.7

来源:互联网 发布:手机必备软件大全2016 编辑:程序博客网 时间:2024/06/07 11:43

先装个MySQLdb   点击打开 

操作数据的的一些方法:
db=MySQLdb.connect(......):连接数据库
cur=db.cursor():获取游标
数据库连接对事务操作的方法:
commit() 提交    
rollback() 回滚

cursor的一些方法:
cur.callproc(procname,args)
用来执行存储过程,接收的参数为存储过程名和参数列表,返回值为受影响的行数
cur.execute(query,[args])
执行单条sql语句,接收的参数为sql语句本身和使用的参数列表,返回值为受影响的行数
cur.executemany(query, args)
执行单条sql语句,但是重复执行参数列表里的参数,返回值为受影响的行数
cur.nextset()
移动到下一个结果集
cur.fetchone()
该方法获取下一个查询结果集。结果集是一个元祖
cur.fetchall()
接收全部的返回结果行.
cur.fetchmany(size=None)
接收size条返回结果
cur.scroll(value,mode='relative')
移动指针到某一行。
          value为移动的行数
          mode为relative时,表示从当前所在行移动value条
          mode为absolute时,表示从结果集的第一行移动value条。
cur.rowcount:这是一个只读属性,并返回执行execute()方法后影响的行数。

连接数据库大致分为以下步骤:
  (1)建立和数据库系统的连接
  (2)获取cursor游标
  (3)执行SQL语句,创建一个数据库(如果已经存在需要操作的数据库,则跳过)
  (4)选择数据库
  (5)执行各种数据库操作
  (6)操作完毕后,提交事务(提交事务后,数据才能真正写入数据库)
  (7)关闭cursor游标
  (8)关闭数据库连接

插入数据:(增)

#encoding=utf-8import MySQLdb#打开数据库 host为本地;user为安装mysql时创建的用户,默认为root;passwd为安装mysql时设置的用户密码 还可以直接在后面添加要操作的数据库db="..."db=MySQLdb.connect(host="localhost",user="root",passwd="Password",charset="utf8")#数据库中有中文避免乱码 加上charset="utf-8"或者charset="gb2312"#使用cursor获取操作游标cursor=db.cursor()#SQL语句 创建数据库cursor.execute("CREATE DATABASE IF NOT EXISTS StudentDB")#SQL语句 选择数据库db.select_db("StudentDB")#删除数据库:cursor.execute("DROP DATABASE IF EXISTS StudentDB") #SQL语句  创建表cursor.execute("CREATE TABLE IF NOT EXISTS Students(Id Int,Name varChar(16) NOT NULL,Sex Char(2),Score Float)")#删除表:cursor.execute("DROP TABLE IF EXISTS Students")#SQL语句  插入数据cursor.execute('INSERT INTO Students(Id,Name,Sex,Score) VALUES(1,"SF","女",100.0)')cursor.execute('INSERT INTO Students(Id,Name,Sex,Score) VALUES(2,"ZJ","F",99.0)')cursor.execute('INSERT INTO Students(Id,Name,Sex,Score) VALUES(3,"MX","F",98.0)')cursor.execute('INSERT INTO Students(Id,Name,Sex,Score) VALUES(4,"MF","F",97.0)')cursor.execute('INSERT INTO Students(Id,Name,Sex,Score) VALUES(5,"ZG","F",66.0)')#查询数据库所有字段的数据  *表示查询所有  也可以使用Id 、Name等具体字段名count=cursor.execute("SELECT * FROM Students")print"总共有"+str(count)+"条记录"rows=cursor.fetchall() #此方法返回一元组 用于存放查询处理的数据  #遍历元组 输出数据for row in rows:    print row[0],row[1],row[2],row[3]   #提交到数据库执行db.commit()#关闭数据库连接db.close()

删除数据:(删)

#encoding=utf-8import MySQLdbdb=MySQLdb.connect(host="localhost",user="root",passwd="Password",charset="utf8")cursor=db.cursor()db.select_db("StudentDB")#删除Students表中Name=ZG的数据cursor.execute("DELETE FROM Students WHERE Name='ZG'")count=cursor.execute("SELECT * FROM Students")print"总共有"+str(count)+"条记录"rows=cursor.fetchall()for row in rows:    print row[0],row[1],row[2],row[3]   db.commit()db.close()

更新数据:(改)

#encoding=utf-8import MySQLdbdb=MySQLdb.connect(host="localhost",user="root",passwd="Password",charset="utf8")cursor=db.cursor()db.select_db("StudentDB")#SQL语句 更新数据库数据内容 将Name=MF的那一条数据的Id字段值增1cursor.execute("UPDATE Students SET Id=Id+1 WHERE Name='MF'")count=cursor.execute("SELECT * FROM Students")print"总共有"+str(count)+"条记录"rows=cursor.fetchall()for row in rows:    print row[0],row[1],row[2],row[3]   db.commit()db.close()

根据条件查询:(查)

#encoding=utf-8import MySQLdbdb=MySQLdb.connect(host="localhost",user="root",passwd="Password",charset="utf8")cursor=db.cursor()db.select_db("StudentDB")#查询数据库所有字段的数据并且满足条件Sex=女或Score>98count=cursor.execute("SELECT * FROM Students WHERE Sex='女'OR Score>98")#或者count=cursor.execute("SELECT * FROM Students WHERE Sex='%s'OR Score>'%f'"%('女',98))print"总共有"+str(count)+"条记录"rows=cursor.fetchall()  for row in rows:    print row[0],row[1],row[2],row[3]   db.commit()db.close()

删除表语删除数据库:

#encoding=utf-8import MySQLdbdb=MySQLdb.connect(host="localhost",user="root",passwd="Password",charset="utf8")cursor=db.cursor()#删除数据库StudentDBcursor.execute("DROP DATABASE IF EXISTS StudentDB")#创建数据库StudentDBcursor.execute("CREATE DATABASE IF NOT EXISTS StudentDB")db.select_db("StudentDB")#删除数据的表Studentscursor.execute("DROP TABLE IF EXISTS Students")#创建数据库表Studentscursor.execute("CREATE TABLE IF NOT EXISTS Students(Id Int,Name varChar(16) NOT NULL,Sex Char(2),Score Float)")db.commit()db.close()

增删改查:

#encoding=utf-8import MySQLdbdb=MySQLdb.connect(host="localhost",user="root",passwd="Password",charset="utf8")cursor=db.cursor()cursor.execute("CREATE DATABASE IF NOT EXISTS Mydatabase")db.select_db("Mydatabase")#Id int NOT NULL AUTO_INCREMENT PRIMARY KEY设置Id为主键自增长cursor.execute("CREATE TABLE IF NOT EXISTS Mytable(Id int AUTO_INCREMENT PRIMARY KEY,Name varChar(6)NOT NULL)")#增print"增"cursor.execute("INSERT INTO Mytable(Name)VALUES('GSZ')")cursor.execute("INSERT INTO Mytable(Name)VALUES('ZSG')")cursor.execute("INSERT INTO Mytable(Name)VALUES('GZS')")cursor.execute("INSERT INTO Mytable(Name)VALUES('ZZZ')")#ORDER BY Id DESC根据Id降序排序cursor.execute("SELECT * FROM Mytable ORDER BY Id DESC")rows=cursor.fetchall()for row in rows:    print row[0],row[1]#删print"删"cursor.execute("DELETE FROM Mytable WHERE Name='ZZZ'")#ORDER BY Id ASC根据Id升序排序count=cursor.execute("SELECT * FROM Mytable ORDER BY Id ASC")for i in range(0,count):    row=cursor.fetchone()    print row[0],row[1]#改print"改"#cursor.execute("UPDATE Mytable SET Id=6 WHERE Name='GZS'")cursor.execute("UPDATE Mytable SET Name='SZG' WHERE Name='ZSG'")cursor.execute("SELECT * FROM Mytable")update_rows=int(cursor.rowcount)for i in range(0,update_rows):    row=cursor.fetchone()    print row[0],row[1]#查print"查"count=cursor.execute("SELECT * FROM Mytable WHERE Id=6")print"总共有"+str(count)+"条记录"rows=cursor.fetchall()for row in rows:    print row[0],row[1]   db.commit()db.close()
                                             
0 0
原创粉丝点击