zoukankan      html  css  js  c++  java
  • 数据库编程

    操作SQLite3数据库

    从Python3.x版本开始,在标准库中已经内置了SQLlite3模块,它可以支持SQLite3数据库的访问和相关的数据库操作。在需要操作SQLite3数据库数据时,只须在程序中导入SQLite3模块即可。Python语言操作SQLite3数据库的基本流程如下所示。
    (1) 导入相关库或模块(SQLite3)。
    (2) 使用connect()连接数据库并获取数据库连接对象。它提供了以下方法:.cursor() 方法来创建一个游标对象

    • .commit() 方法来处理事务提交
    • .rollback() 方法来处理事务回滚
    • .close() 方法来关闭一个数据库连接
      (3) 使用con.cursor()获取游标对象。
      (4) 使用游标对象的方法(execute()、executemany()、fetchall()等)来操作数据库,实现插入、修改和删除操作,并查询获取显示相关的记录。在Python程序中,连接函数sqlite3.connect()有如下两个常用参数。database:表示要访问的数据库名。timeout:表示访问数据的超时设定。
      (5) 使用close()关闭游标对象和数据库连接。数据库操作完成之后,必须及时调用其close()方法关闭数据库连接,这样做的目的是减轻数据库服务器的压力。
      使用SQLite3创建表
      使用sqlite3模块的connect方法来创建/打开数据库,需要指定数据库路径,不存在则创建一个新的数据库。
    con = sqlite3.connect("'e:/sqllitedb/first.db'")

    使用SQLite3创建表

    #导入sqllite3模块
    import sqlite3#
    #1.在硬盘上创建连接
    con = sqlite3.connect("'e:/sqllitedb/first.db'")
    # 获取cursor对象
    cur = con.cursor()
    # 执行sql创建表sql = 'create table t_person(pno INTEGER PRIMARY KEY  AUTOINCREMENT ,pname varchar(30) NOT NULL ,age INTEGER)'
    try:    
    	cur.execute(sql)
    except Exception as e:    
    	print(e)    
    	print('创建表失败')
    finally:    
    	# 关闭游标    
    	cur.close()    
    	# 关闭连接    
    	con.close()

    使用SQLite3插入数据
    调用游标对象的execute执行插入的sql,使用executemany()执行多条sql语句,使用executmany()比循环使用excute()执行多条sql语句效率高。
    使用SQLite3插入一条数据

    #导入sqllite3模块
    import sqlite3
    # 1.硬盘上创建连接
    con = sqlite3.connect('e:/sqlitedb/first.db')
    # 获取cursor对象
    cur = con.cursor()
    # 执行sql创建表
    sql = 'insert into t_person(pname,age) values(?,?)'
    try:    	
    	cur.execute(sql,('张三',23))    
    	#提交事务    
    	con.commit()    
    	print('插入成功')
    except Exception as e:    
    	print(e)    
    	print('插入失败')    
    	con.rollback()
    finally:    
    	# 关闭游标
    	cur.close()    
    	# 关闭连接    
    	con.close()

    使用SQLite3插入多条数据

    #导入sqllite3模块
    import sqlite3 
    # 1.硬盘上创建连接
    con = sqlite3.connect('e:/sqlitedb/first.db')
    # 获取cursor对象
    cur = con.cursor()
    try:    
    	#执行sql创建表    
    	sql = 'insert into t_person(pname,age) values(?,?)'    
    	cur.executemany(sql, [('张三', 23), ('李四', 25), ('小红', 24), ('小李', 12)])    	 	    
    	#提交事务
    	con.commit()    
    	print('插入成功')
    except Exception as e:    
    	print('插入失败')    
    	con.rollback()
    finally:    
    	# 关闭游标    
    	cur.close()    
    	# 关闭连接    
    	con.close()

    使用SQLite3查询数据
    查询数据,游标对象提供了fetchall()和fetchone()方法 。fetchall()方法获取所有数据,返回一个列表。fetchone()方法获取其中一个结果,返回一个元组。
    fetchall()查询所有数据

    #导入sqllite3模块
    import sqlite3
    # 1.硬盘上创建连接
    con = sqlite3.connect('e:/sqlitedb/first.db')
    # 获取cursor对象
    cur = con.cursor()
    # 执行sql创建表
    sql = 'select * from t_person'
    try:    
    	cur.execute(sql)    
    	# 获取所有数据    
    	person_all = cur.fetchall()    
    	# print(person_all)    
    	# 遍历    
    	for p in person_all:        
    		print(p)
    except Exception as e:    
    	print(e)    
    	print('查询失败')
    finally:    
    	# 关闭游标    
    	cur.close()    
    	# 关闭连接    
    	con.close()

    fetchone()查询一条数据

    #导入sqllite3模块
    import sqlite3 
    # 1.硬盘上创建连接
    con = sqlite3.connect('e:/sqlitedb/first.db')
    # 获取cursor对象
    cur = con.cursor()
    # 执行sql创建表
    sql = 'select * from t_person'
    try:    
    	cur.execute(sql)    
    	# 获取一条数据    
    	person = cur.fetchone()    
    	print(person)
    	except Exception as e:    
    	print(e)    
    	print('查询失败')
    	finally:    
    	# 关闭游标    
    	cur.close()    
    	# 关闭连接    
    	con.close()

    修改数据

    #导入sqllite3模块
    import sqlite3
    #1.硬盘上创建连接
    con=sqlite3.connect('e:/sqlitedb/first.db')
    #获取cursor对象
    cur=con.cursor()
    try:    
    	#执行sql创建表    
    	update_sql = 'update t_person set pname=? where pno=?'
    	cur.execute(update_sql, ('小明', 1))        	  
    	#提交事务    
    	con.commit()    
    	print('修改成功')
    except Exception as e:    
    	print(e)    
    	print('修改失败')
    	con.rollback()
    finally:    
    	# 关闭游标    
    	cur.close()    
    	# 关闭连接    
    	con.close()

    删除数据

    #导入sqllite3模块
    import sqlite3
    #1.硬盘上创建连接
    con=sqlite3.connect('e:/sqlitedb/first.db')
    #获取cursor对象
    cur=con.cursor()
    #执行sql创建表
    delete_sql = 'delete from t_person where pno=?'
    try:    
    	cur.execute(delete_sql, (2,))    
    	#提交事务    
    	con.commit()    
    	print('删除成功')
    except Exception as e:    
    	print(e)    
    	print('删除失败')    
    	con.rollback()
    finally:    
    	# 关闭游标    
    	cur.close()    
    	# 关闭连接    
    	con.close()

    在上述实例代码中,首先定义查询所有数据、插入数据、修改数据、删除数据的方法。然后,定义主方法中依次建立连接,获取连接的cursor,通过cursor的execute()等方法来执行SQL语句,调用插入记录、更加记录、删除记录的方法。

    创建数据库表

    在Python程序中,可以使用execute()在数据库中创建一个新表。下面的实例代码演示了在PyMySQL数据库中创建新表student的过程。
    创建表student

    import pymysql
    try:    
    	#创建与数据库的连接    
    	db=pymysql.connect('localhost','root','root','testdb')    
    	#创建游标对象cursor    
    	cursor=db.cursor()    
    	#使用execute()方法执行sql,如果表存在则删除    
    	cursor.execute('drop table if EXISTS student')    
    	#创建表的sql    
    	sql='''        
    		create table student(        
    		sno int(8) primary key auto_increment,        
    		sname varchar(30) not null,        
    		sex varchar(5) ,        
    		age int(2),        
    		score float(3,1)        
    		)    
    	'''    
    	cursor.execute(sql)
    except:    
    	print('创建表失败')
    finally:    
    	#关闭数据库连接    
    	db.close()

    数据库插入操作
    在Python程序中,可以使用SQL语句向数据库中插入新的数据信息。
    向student表中插入数据信息

    import pymysql
    #创建与数据库的连接
    db=pymysql.connect('localhost','root','root','testdb')
    #创建游标对象
    cursorcursor=db.cursor()
    #插入sql语句
    sql='''    
    	insert into student(sname,sex,age,score) values(%s,%s,%s,%s)
    '''
    try:    
    	#执行sql语句    
    	cursor.execute(sql,('李四','woman',25,99.6))    
    	#提交事务    
    	db.commit()    
    	print('插入成功')
    except Exception as e:    
    	print(e)    
    	#如果出现异常,回滚    
    	db.rollback()    
    	print('插入失败')
    finally:    
    	#关闭数据库连接    
    	db.close()

    向student表同时插入多条数据

    import pymysql
    #创建与数据库的连接
    db=pymysql.connect('localhost','root','root','testdb')
    #创建游标对象
    cursorcursor=db.cursor()
    #插入sql语句
    sql='''    
    	insert into student(sname,sex,age,score) values(%s,%s,%s,%s)
    '''
    args=[('王五','woman',22,98.6),('赵六','man',21,99.1)]
    try:    
    	#执行sql语句    
    	cursor.executemany(sql,args)    
    	#提交事务    
    	db.commit()    
    	print('插入成功')
    except Exception as e:
    	print(e)    
    	#如果出现异常,回滚    
    	db.rollback()    
    	print('插入失败')
    finally:    
    	#关闭数据库连接    
    	db.close()

    数据库查询操作
    Python查询Mysql使用 fetchone() 方法获取单条数据, 使用fetchall() 方法获取多条数据。
    fetchone(): 该方法获取下一个查询结果集。结果集是一个对象
    fetchall(): 接收全部的返回结果行.
    rowcount: 这是一个只读属性,并返回执行execute()方法后影响的行数。
    查询学生 年龄大于等于23的所有学生信息

    import pymysql
    #创建与数据库的连接
    db=pymysql.connect('localhost','root','root','testdb')
    #创建游标对象
    cursorcursor=db.cursor()
    #查询年龄大于等于23的所有学生信息
    sql='select * from student where age>=23'
    try:    
    	#执行sql    
    	cursor.execute(sql)    
    	#获取查询结果    
    	results=cursor.fetchall()    
    	for row in results:        
    		sno=row[0]        
    		sname=row[1]        
    		sex=row[2]        
    		age=row[3]        
    		score=row[4]        
    		#输出
    		print('sno:',sno,'sname:',sname,'sex:',sex,'age:',age,'score:',score)     
    except Exception as e:    
    	print(e)    
    	print('查询失败')
    finally:    
    	db.close()   		

    数据库更新操作
    在Python程序中,可以使用update语句更新数据库中数据信息。

    import pymysql
    #创建与数据库的连接
    db=pymysql.connect('localhost','root','root','testdb')
    #创建游标对象
    cursorcursor=db.cursor()
    #将sno=5的学生成绩修改为99.5
    sql='update student set score=%s where sno=%s'
    try:    
    	#执行sql    
    	cursor.execute(sql,(99.5,5))    
    	#提交数据    
    	db.commit()    
    	print('修改成功')
    except:    
    	print('修改失败')    
    	db.rollback()
    finally:    
    	db.close()

    数据库删除操作
    在Python程序中,可以使用delete语句删除数据库中的数据信息
    删除年龄小于22的学生

    import pymysql
    #创建与数据库的连接
    db=pymysql.connect('localhost','root','root','testdb')
    #创建游标对象
    cursorcursor=db.cursor()
    #删除
    sqlsql='delete from student where age < 22'
    try:    
    	#执行sql语句    
    	cursor.execute(sql)    
    	#提交事务    
    	db.commit()    
    	print('删除数据成功')
    except:    
    	db.rollback()    
    	print('删除数据失败')
    finally:    
    	#关闭连接   
    	db.close()
    别废话,拿你代码给我看。
  • 相关阅读:
    使用java写一个小白计算器
    UVALive 6911 Double Swords (Set,贪心,求区间交集)
    UVALive 6910 Cutting Tree(并查集应用)
    Gym 101102C Bored Judge(set--结构体集合)
    有序链表和顺序表
    Gym 101102B The Little Match Girl(贪心+规律)
    UVALive 7070 The E-pang Palace(暴力)
    数据库系统实现 第二章 数据存储
    数据库系统实现 第一章 DBMS实现概述
    数据库系统实现 第六章 查询执行
  • 原文地址:https://www.cnblogs.com/lvxueyang/p/13707515.html
Copyright © 2011-2022 走看看