首页 > 编程语言 >Python第十一周

Python第十一周

时间:2022-12-14 18:34:06浏览次数:63  
标签:execute Python 第十一 db cursor user close conn

一、实验目的和要求

1、学会数据库编程接口;

2、学会使用SQLite;

3、学会使用MySQL。

二、实验环境

Python 3.10 64_bit

三、实验过程

实例一

代码如下:

 1 import sqlite3
 2 # 连接到SQLite数据库
 3 # 数据库文件是mrsoft.db,如果文件不存在,会自动在当前目录创建
 4 conn = sqlite3.connect('mrsoft.db')
 5 # 创建一个Cursor
 6 cursor = conn.cursor()
 7 # 执行一条SQL语句,创建user表
 8 cursor.execute("create table user (id int(10) primary key, name varchar(29))")
 9 # 关闭游标
10 cursor.close()
11 # 关闭Connection
12 conn.close()

 

实例二

代码如下:

 1 import sqlite3
 2 # 连接到sQlite数据库
 3 # 数据库文件是mrsoft.db
 4 # 如果文件不存在,会自动在当前目录创建
 5 conn = sqlite3.connect('mrsoft.db')
 6 # 创建一个Cursor
 7 cursor = conn.cursor()
 8 #执行一条SQL语句,插入一条记录
 9 cursor.execute('insert into user (id, name) values ("1", "MRSOFT")')
10 cursor.execute('insert into user (id, name) values ("2","Andy")')
11 cursor.execute('insert into user (id, name) values ("3","明日科技小助手")')
12 # 关闭游标
13 cursor.close()
14 # 提交事务
15 conn.commit()
16 # 关闭Connection
17 conn.close()

 

实例三

代码如下:

 1 import sqlite3
 2 # 连接到SQLite数据库,数据库文件是mrsoft.db
 3 conn =sqlite3.connect("mrsoft.db")
 4 # 创建一个Cursor
 5 cursor =conn.cursor()
 6 #执行查询语句
 7 cursor.execute("select * from user where id > ?",(0,))
 8 # 获取查询结果
 9 result1 = cursor.fetchall()
10 print(result1)
11 # 关闭游标
12 cursor.close()
13 # 关闭Connection
14 conn.close()

 

实例四

代码如下:

 1 import sqlite3
 2 # 连接到sQLite数据库,数据库文件是mrsoft.db
 3 conn = sqlite3.connect('mrsoft.db')
 4 # 创建一个Cursor:
 5 cursor =conn.cursor()
 6 cursor.execute("update user set name = ? where id = ?",("MR",1))
 7 cursor.execute("select * from user")
 8 result = cursor.fetchall()
 9 print(result)
10 # 关闭游标
11 cursor.close()
12 # 提交事务
13 conn.commit()
14 # 关闭Connection:
15 conn.close()

运行结果:

 

 

 

实例五

代码如下:

 1 import sqlite3
 2 # 连接到SQLite数据库,数据库文件是mrsoft.db
 3 conn = sqlite3.connect("mrsoft.db")
 4 # 创建一个Cursor:
 5 cursor = conn.cursor()
 6 cursor.execute("delete from user where id = ?",(1,))
 7 cursor.execute("delete from user where id = ?",(2,))
 8 cursor.execute("delete from user where id = ?",(3,))
 9 cursor.execute("select * from user")
10 result = cursor.fetchall()
11 print(result)
12 # 关闭游标
13 cursor.close()
14 # 提交事务
15 conn.commit()
16 # 关闭Connection:
17 conn.close()

运行结果:

 

 

实例六

代码如下:

 1 import pymysql
 2 # 打开数据库连接,host:主机名或IP;user:用户名;password:密码;database:数据库名称
 3 db = pymysql.connect(host="localhost",user= "root",password= "root",database= "mrsoft")
 4 #使用cursor()方法创建一个游标对象cursor
 5 cursor=db.cursor()
 6 # 使用execute()方法执行SQL查询
 7 cursor.execute("SELECT VERSION()")
 8 # 使用fetchone()方法获取单条数据
 9 data=cursor.fetchone()
10 print("Database version : %s " % data)
11 # 关闭数据库链接
12 db.close()

运行结果:

 

 

实例七

代码如下:

 1 import pymysql
 2 #打开数据库连接
 3 db=pymysql.connect(host="localhost",user= "root",password= "root",database= "mrsoft")
 4 # 使用cursor()方法创建一个游标对象cursor
 5 cursor = db.cursor()
 6 # 使用execute()方法执行SQL,如果表存在则删除
 7 cursor.execute("DROP TABLE IF EXISTS books")
 8 # 使用预处理语句创建表
 9 sql = """
10 CREATE TABLE books (
11   id int(8) NOT NULL AUTO_INCREMENT,
12   name varchar(50) NOT NULL,
13   category varchar(50) NOT NULL,
14   price decimal(10,2) DEFAULT NULL,
15   publish_time date DEFAULT NULL,
16   PRIMARY KEY (id)
17 ) ENGINE=MyISAM AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;
18 """
19 # 执行SQL语句
20 cursor.execute(sql)
21 #关闭数据库连接
22 db.close()

 

实例八

代码如下:

 1 import pymysql
 2 # 打开数据库连接
 3 db=pymysql.connect(host="localhost",user="root",password="root",database="mrsoft",charset="utf8")
 4 # 使用cursor()方法获取操作游标
 5 cursor =db.cursor()
 6 # 数据列表
 7 data=[("零基础学Python","Python","79.80","2018-5-20"),
 8       ("Python从入门到精通","Python","69.80","2018-6-18"),
 9       ("零基础学PHP","PHP","69.80","2017-5-21"),
10       ("PHP项目开发实战入门","PHP","79.80","2016-5-21"),
11       ("零基础学]ava","Java","69.80","2017-5-21"),
12       ]
13 try:
14     #执行sq1语句,插入多条数据
15     cursor.executemany("insert into books(name, category, price, publish_time) values (%s,%s,%s,%s)",data)
16 # 提交数据
17     db.commit()
18 except:
19     # 发生错误时回滚
20     db.rollback()
21     # 关闭数据库连接
22     db.close()

 

实战一

代码如下:

1 import pymysql
2 db = pymysql.connect(host="localhost",user= "root",password= "root",database= "mrsoft")
3 cursor = db.cursor()
4 cursor.execute("select name,price from books")
5 result = cursor.fetchall()
6 for i in range(0,len(result)):
7     print("图书:《" + str(result[i][0]) + "》,价格:¥" + str(result[i][1]) + "元")
8 cursor.close()
9 db.close()

运行结果:

 

 

实战二

代码如下:

1 import pymusql
2 conn = pymusql.connect(host="localhost",user= "root",password= "root",database= "mrsoft")
3 cursor = db.cursor()
4 cursor.execute("select name,price,publish_time from books where int(price) < 70 and publish >= '2017'")
5 result1 = cursor.fetchall()
6 for i in range(0,len(result)):
7     print("图书:《" + result[i][0] + "》,价格:¥", + result[i][1] + "元,出版日期:" + result[i][2])
8 cursor.close()
9 db.close()

运行结果:

 

 

实战三

代码如下:

 1 import pymusql
 2 conn = pymusql.connect(host="localhost",user= "root",password= "root",database= "mrsoft")
 3 cursor = db.cursor()
 4 cursor.execute("delete from books where category = PHP")
 5 cursor.execute("select name,price from books")
 6 result1 = cursor.fetchall()
 7 for i in range(0,len(result)):
 8     print("图书:《" + result[i][0] + "》,价格:¥", + result[i][1] + "元")
 9 cursor.close()
10 db.close()

运行结果:

 

标签:execute,Python,第十一,db,cursor,user,close,conn
From: https://www.cnblogs.com/yisheng8/p/16982929.html

相关文章

  • python实验报告(第8章)
    实例01:创建计算BMi指数的模块 创建一个用于根据身高、体重计算BMI指数的模块,命名为bmi.py,其中bmi为模块名,.py为扩展名。 代码如下:1deffun_bmi(pers......
  • Python实验报告(第9章)
    实例一:实验相关代码:defdivision():'''功能:分苹果'''print("\n==================分苹果了=================\n")apple=int(input("请输入苹......
  • Python调试工具
     Cyberbrain:Pythondebugging, redefined.https://github.com/laike9m/Cyberbrainhttps://github.com/cool-RR/PySnooper https://pythontutor.com/Pythontutor......
  • python3 安装 impyla
    pip3installsixbit_arraybitarraypip3installthriftpy==0.3.8pure-saslpip3installthrift-sasl==0.2.1--no-depspip3installimpyla==0.14.1如果出现异常pip3in......
  • Python3.9+Sqlite3
    python&sqlite简介Sqlite3作为Python内置的数据库,不需要再单独下载sqlite,直接import即可。使用python操作sqlite创建并连接数据库也可以把数据库名称指定为:memory:,这样......
  • Python 实验报告(第6章)
    实例一:输出每日一贴(共享版) 代码如下:deffunction_tips():'''功能:每天输出一条励志文字'''importdatetime#导入日期时间类#......
  • Python数据压缩和存档——zlib/gzip/bzip2/lzma/zip/tar
    Python数据压缩和存档——zlib/gzip/bzip2/lzma/zip/tar​前言python中提供了几种重要的数据压缩算法的支持,包括zlib、gzip、bzip2和lzma数据压缩算法,同时支持创建ZIP......
  • Python 闭包
    闭包概念闭包,又称闭包函数或者闭合函数,其实和前面讲的嵌套函数类似,不同之处在于,闭包中外部函数返回的不是一个具体的值,而是一个函数。一般情况下,返回的函数会赋值给一个变......
  • python json使用
    本质:字典和json字符串相互转换json.dumps将一个Python数据结构转换为JSONimportjsondata={'name':'myname','age':100,}json_str=json.dumps(d......
  • python学习笔记整理02(判断、循环)
    程序开发中有三大流程:顺序、分支、循环 一、顺序:代码从上到下,依次执行 二、分支:判断语句,代码有选择的执行if判断条件1:书写条件1成立(真),执行的代码#判断条......