python之数据库编程

sqlite

1.前期准备工作

  • 导入模块:

    import sqlite3
  • 连接数据库

    conn = sqlite3.connect("test.db")  #test为数据库名称,若不存在此数据库,会自动创建
  • 测试是否创建或连接数据库成功

    print(conn)  #打印结果为connection对象
  • pycharm端显示出数据库:

    • 1.打开pycharm->右端database->点击+号

  • 2.第二步:

  • 3.第三步

  • 4.选择pycharm工作环境下新创建的数据库,比如我的在这里

点击ok即可,注意:

若第三步出现这个,点击Download先进行下载。。。

2.创建数据库和表

import sqlite3
conn = sqlite3.connect("test.db")
#cur = conn.cursor()
sql = """
CREATE TABLE test(
id INTEGER PRIMARY KEY autoincrement,
name TEXT,
age INTEGER
)
"""
try:
#cur.execute(sql)
conn.execute(sql)
except Exception as e:
print(e)
finally:
#cur.close()
conn.close()

注意:

可以看到,此处并没有使用游标,而是直接conn.execute(sql),值得说明的是,对sqlite来说(mysql却不是),增删改以及创建表都可以不用游标,但查询一定需要,往下看

3.插入数据

import sqlite3
conn = sqlite3.connect('test.db')
# cur = conn.cursor()
sql = """
insert into test(name, age) VALUES (%s,%s)
"""%("'王五'",22)
sql1 = """
insert into test(name, age) VALUES (?,?)
"""
try:
print("sql:"+sql)
print("sql1:" + sql1)
#conn.execute(sql)
#conn.execute(sql1, ('张三', 20))添加单条数据
conn.executemany(sql1,[('李四',18),('王五',28),('赵六',38)])
conn.commit()
print("插入成功")
except Exception as e:
print(e)
print("插入失败")
conn.rollback()
finally:
conn.close()

显示结果:

插入数据中使用了两种方法,见sql和sql1,分别使用%s和?占位符

以下我就不一一展示显示结果了。。。

4.修改数据

import sqlite3
conn = sqlite3.connect('test.db')
# cur = conn.cursor()
sql = """
update test set name = ? , age = ? where id = ?
"""
sql1 = """
update test set name = %s , age = %s where id = %s
"""%("'曹操'", 24, 11)
try:
#conn.execute(sql, ('曹操', 24, 4))
conn.execute(sql1)
print("成功")
conn.commit()
except Exception as e:
print(e)
print("失败")
conn.rollback()
finally:
conn.close()

修改数据中使用了两种方法,见sql和sql1,分别使用%s和?占位符

5.删除数据

import sqlite3
conn = sqlite3.connect('test.db')
#cur = conn.cursor()
sql = """
delete from test where name = ?
"""
sql1 = """
delete from test where name = %s
"""%("'曹操'",)
try:
conn.execute(sql1);
#conn.execute(sql,('曹操',));
#若执行conn.execute(sql,('曹操'));会报错Incorrect number of bindings supplied. The current statement uses 1, and there are 2 supplied.
#使用('曹操',)或[曹操]
conn.commit()
except Exception as e:
conn.rollback()
print(e)
finally:
conn.close()

6.查询数据

import sqlite3
conn = sqlite3.connect('test.db')
cur = conn.cursor()
sql = """
select * from test
"""
try:
cur.execute(sql);
# print(cur.fetchall())#查询所有数据
print(cur.fetchone()) # 查询第一条数据
# print(cur.fetchmany(3))#查询几条数据,从开头开始
except Exception as e:
print(e)
finally:
cur.close()
conn.close()

可以看到,查询数据必须要用游标,按条件进行查询可参照上面的占位符进行测试

7.模糊查询

import sqlite3
conn = sqlite3.connect('test.db')
cur = conn.cursor()
sql = "select * from test where name like '%%%s%%'"%"王"
#sql1 = "select * from test where name like ?"
try:
print(sql)
cur.execute(sql);
#cur.execute(sql1, ("%王%",));
print(cur.fetchall()) # 查询所有数据
# print(cur.fetchone()) # 查询第一条数据
# print(cur.fetchmany(3))#查询几条数据,从开头开始
except Exception as e:
print(e)
finally:
cur.close()
conn.close()

模糊查询中使用了两种方法,见sql和sql1,分别使用%s和?占位符

注意:%s占位符模糊查询时,使用%%---%%进行转义

mysql

1.前期准备工作

  • 导入模块:

    import pymysql
  • 连接数据库

    conn = pymysql.connect(user='root',password='000000',host='localhost',
    port=3306,database='python_test')
    #mysql数据库不会自动创建,需要自己建立
  • 测试是否连接数据库成功

    print(conn)  #打印结果为connection对象
  • pycharm端显示出数据库:

与sqlite操作一样,此时建立的是mysql

2.创建数据库和表

import pymysql
conn = pymysql.connect(user='root',password='000000',host='localhost',
port=3306,database='python_test')
cur = conn.cursor()
sql = """
create table student(
id integer primary key auto_increment,
sno char(20) not null,
name char(20),
score float
)
"""
try:
cur.execute(sql)
print("建表成功")
except Exception as e:
print(e)
print("建表失败")
finally:
cur.close()
conn.close()

注意:

可以看到,与sqlite不同,mysql的操作都需要游标参与

3.插入数据

import pymysql
conn = pymysql.connect(user='root', password='000000', host='localhost', port=3306, database='python_test')
cur = conn.cursor()
sql = """
insert into student(sno, name, score)
values
(%s,%s,%s)
"""
try:
#cur.execute(sql, ('7777', 'ff', 90)) #插入一条
cur.executemany(sql,[('3333','c',3),('4444','d',4)]) #插入多条
conn.commit()
print("插入成功")
except Exception as e:
print(e)
conn.rollback()
print("插入失败")
finally:
cur.close()
conn.close()

显示结果:

mysql中使用%s做占位符

4.修改数据

import pymysql
conn = pymysql.connect(user='root', password='000000', host='localhost', port=3306, database='python_test')
cur = conn.cursor()
sql = """
update student set name = %s where id = %s
"""
try:
cur.execute(sql,('王五',5))
#cur.executemany(sql,[('3333','c',3),('4444','d',4)])
conn.commit()
print("修改成功")
except Exception as e:
print(e)
conn.rollback()
print("修改失败")
finally:
cur.close()
conn.close()

5.删除数据

import pymysql

conn = pymysql.connect(user='root', password='000000', host='localhost', port=3306, database='python_test')
cur = conn.cursor()
sql = """
delete from student where name = %s
"""
try:
cur.execute(sql,'d')
#cur.executemany(sql,[('3333','c',3),('4444','d',4)])
conn.commit()
print("删除成功")
except Exception as e:
print(e)
conn.rollback()
print("删除失败")
finally:
cur.close()
conn.close()

6.查询数据

import pymysql

conn = pymysql.connect(user='root', password='000000', host='localhost', port=3306, database='python_test')
cur = conn.cursor()
sql = """
select * from student
"""
try:
cur.execute(sql)
#print(cur.fetchone())
#print(cur.fetchmany(3))
print(cur.fetchall())
except Exception as e:
print(e)
finally:
cur.close()
conn.close()

7.模糊查询

import pymysql

conn = pymysql.connect(user='root', password='000000', host='localhost', port=3306, database='python_test')
cur = conn.cursor()
sql = """
select * from student where name like %s
"""
sql1 = "select * from student where name like '%%%s%%'"%'王'
try:
print(sql1)
cur.execute(sql1)
#print(cur.fetchone())
#print(cur.fetchmany(3))
print(cur.fetchall())
except Exception as e:
print(e)
finally:
cur.close()
conn.close()

python之数据库编程的更多相关文章

  1. 运用Python语言编写获取Linux基本系统信息(三):Python与数据库编程,把获取的信息存入数据库

    运用Python语言编写获取Linux基本系统信息(三):Python与数据库编程 有关前两篇的链接: 运用Python语言编写获取Linux基本系统信息(一):获得Linux版本.内核.当前时间 运 ...

  2. python的数据库编程

    数据库的基础知识 一.数据库的概念 数据库将大量数据按照一定的方式组织并存储起来,是相互关联的数据的集合.数据库中的数据不仅包括描述事物数据的本身,还包括相关数据之间的联系.数据库可以分为关系型数据库 ...

  3. Python学习系列(七)( 数据库编程)

    Python学习系列(七)( 数据库编程)        Python学习系列(六)(模块) 一,MySQL-Python插件       Python里操作MySQL数据库,需要Python下安装访 ...

  4. Python程序设计9——数据库编程

    1 数据持久化 持久化是将内存中的对象存储在关系数据库中,当然也可以存储在磁盘文件.XML数据文件中.实现数据持久化至少需要实现以下3个接口 void Save(object o):把一个对象保存到外 ...

  5. python 闯关之路四(下)(并发编程与数据库编程) 并发编程重点

    python 闯关之路四(下)(并发编程与数据库编程)   并发编程重点: 1 2 3 4 5 6 7 并发编程:线程.进程.队列.IO多路模型   操作系统工作原理介绍.线程.进程演化史.特点.区别 ...

  6. python 教程 第二十章、 数据库编程

    第二十章. 数据库编程 环境设置 1).安装MySQL-python http://www.lfd.uci.edu/~gohlke/pythonlibs/ MySQL-python-1.2.3.win ...

  7. Python黑帽编程 2.0 第二章概述

    Python黑帽编程 2.0 第二章概述 于 20世纪80年代末,Guido van Rossum发明了Python,初衷据说是为了打发圣诞节的无趣,1991年首次发布,是ABC语言的继承,同时也是一 ...

  8. Python金融应用编程(数据分析、定价与量化投资)

    近年来,金融领域的量化分析越来越受到理论界与实务界的重视,量化分析的技术也取得了较大的进展,成为备受关注的一个热点领域.所谓金融量化,就是将金融分析理论与计算机编程技术相结合,更为有效的利用现代计算技 ...

  9. 使用Python管理数据库

    使用Python管理数据库   这篇文章的主题是如何使用Python语言管理数据库,简化日常运维中频繁的.重复度高的任务,为DBA们腾出更多时间来完成更重要的工作.文章本身只提供一种思路,写的不是很全 ...

随机推荐

  1. python爬虫--案例分析之针对简单的html文件

    python爬虫常用的库:Python 库(urllib.BeautifulSoup.requests.scrapy)实现网页爬虫 python爬虫最简单案例分析:  对一个html文件进行分解,获取 ...

  2. 素数(质数)(Java版)

    4.输出质数(素数) 素数(质数):是指在大于1的自然数中,除了1和它本身外,不能被其他自然数整除(除0以外)的数 public class PrimeNumber { public static v ...

  3. springmvc学习指南 之---第27篇 spring如何实现servlet3.0无web.xml 配置servlet对象的

    writedby 张艳涛 基于web.xml配置,有人说麻烦,tomcat给按照servlet3.0,实现了基于注解@WebServlet,有人说springmvc的springmvc.xml配置麻烦 ...

  4. 添加xxx到右键菜单

    1. 添加notepad++到右键菜单[1] 添加到 右键菜单 将以下内容保存为 OpenWithNotepad++.reg 文件,双击运行即可(其中可执行文件路径和菜单项名称请自行替换): 注: 下 ...

  5. Python小白的数学建模课-12.非线性规划

    非线性规划是指目标函数或约束条件中包含非线性函数的规划问题,实际就是非线性最优化问题. 从线性规划到非线性规划,不仅是数学方法的差异,更是解决问题的思想方法的转变. 非线性规划问题没有统一的通用方法, ...

  6. 浅谈vue响应式原理及发布订阅模式和观察者模式

    一.Vue响应式原理 首先要了解几个概念: 数据响应式:数据模型仅仅是普通的Javascript对象,而我们修改数据时,视图会进行更新,避免了繁琐的DOM操作,提高开发效率. 双向绑定:数据改变,视图 ...

  7. fastboot刷机小脚本

    在Windows系统下,一般刷机命令是在cmd路径下执行如下命令: 1.adb reboot bootloader2.fastboot flash boot +boot路径3.fastboot fla ...

  8. C# 事件与继承

    在窗体编程过程中,常常会封装一个基类,包含未来业务中常用的属性.方法.委托.事件等,但是事件作为一个特殊的委托,只能在声明类中调用,派生类都不可以调用,所以在基类中必须实现一个虚函数,实现事件的调用, ...

  9. Java Stream 自定义Collector

    Collector的使用 使用Java Stream流操作数据时,经常会用到各种Collector收集器来进行数据收集. 这里便深入了解一点去了解Collector的工作原理和如何自定义Collect ...

  10. OpenStack中VNC协议实现多屏共享(多屏不踢访问)

    OpenStack中VNC协议实现多屏共享 by 无若   libvirt设置基本说明:   <devices> <graphics type='sdl' display=':0.0 ...