设为首页 收藏本站
查看: 1524|回复: 0

[经验分享] Python数据库访问之SQLite3、Mysql

[复制链接]

尚未签到

发表于 2015-4-20 08:17:18 | 显示全部楼层 |阅读模式
  现有的数据库管理系统有很多种,本文选择介绍两种DBMS:SQLite 3 和 Mysql。
  SQLite 3
  SQLite 3是Python 3预装的、相当完备、无需配置的基于SQL的数据库管理系统。要使用SQLite,只需导入sqlite3库,并使用Python标准化数据库API来编程,而不用处理其他工作,比如:安装数据库、配置等等。




Python数据库API 提供了一种标准机制,可以针各种各样的数据库管理系统,包括SQLite。不管使用什么后台数据库,代码所遵循的过程都是一样的:连接 -> 创建游标 -> 交互(利用游标,使用SQL管理数据)->提交/回滚 ->关闭  示例1:



#导入你需要的库
import sqlite3
#1、建立与数据库的连接
connection=sqlite3.connect('test.db');
#2、创建数据游标
cursor=connection.cursor()
#3、执行一些SQL操作
cursor.execute("""select date('NOW')""")
print(cursor.fetchone())
#4、提交所做的修改,使修改永久保留
connection.commit()
#5、完成时关闭链接
connection.close()
  输出:
  ('2013-06-26',)
  示例2:
  创建数据库 -> 插入数据 -> 查询



import sqlite3
db='test.sqlite'    #数据库名
drop_table_sql="drop table if exists books;"
create_table_sql="""
create table books(
id integer primary key autoincrement unique not null,
name text not null,
price integer,
publish_date date not null
);
"""
connection=sqlite3.connect(db)
cursor=connection.cursor()
#创建数据库
cursor.execute(drop_table_sql)
cursor.execute(create_table_sql)
#插入数据
insert_sql="insert into books (name,price,publish_date) values (?,?,?)"# ? 为占位符
cursor.execute(insert_sql,('java',123.23,'2012-12-03'))
cursor.execute(insert_sql,('C++',83.23,'2013-02-03'))
connection.commit()
#查询
select_sql = "SELECT * FROM books"
cursor.execute(select_sql)
#返回一个list,list中的对象类型为tuple(元组)
data=cursor.fetchall()
for t in data:
print(t)
connection.close()
  输出:
  (1, 'java', 123.23, '2012-12-03')
(2, 'C++', 83.23, '2013-02-03')
  
  Mysql
  Mysql是非常流行的开源关系性数据库。
  要使用Python访问Mysql,需要一个连接库,即对Python DB API的一个实现,相当于JAVA中的MySQL的JDBC Driver。其中比较著名就是MySQLdb(Django项目使用它),不过,目前MySQLdb并不支持python3.x。我们只能采用其他连接库,MySQL官方已经提供了MySQL连接器,而且已经有支持Python3.x的版本了。
  MySQL Connector/Python enables Python programs to access MySQL databases, using an API that is compliant with the Python DB API version 2.0。
关于MySQL Connector/Python的各种介绍、安装、API等文档,请参考官网:http://dev.mysql.com/doc/connector-python/en/index.html
  示例:




import mysql.connector
import sys, os
user = 'root'
pwd  = '123456'
host = '127.0.0.1'
db   = 'test'
connection = mysql.connector.connect(user=user, password=pwd, host=host, database=db)
cursor = connection.cursor()
#创建数据库表
drop_table_sql="drop table if exists person;"
create_table_sql = """
CREATE TABLE person(
id int(10) AUTO_INCREMENT PRIMARY KEY,
name varchar(20),
age int(4)
)CHARACTER SET utf8;
"""
try:
cursor.execute(drop_table_sql)
cursor.execute(create_table_sql)
except mysql.connector.Error as err:
print("create table 'mytable' failed.")
print("Error: {}".format(err.msg))
sys.exit()
#插入数据
insert_sql = 'INSERT INTO person(name, age) VALUES (%s,%s)'
try:
cursor.execute(insert_sql,('Jay', 22))
cursor.execute(insert_sql,('Tony', 26))
cursor.execute(insert_sql,('邵',24))
except mysql.connector.Error as err:
print("insert table 'mytable' failed.")
print("Error: {}".format(err.msg))
sys.exit()
#查询数据
select_sql = "SELECT * FROM person"
try:
#cursor.execute() 返回 None; 执行SQL后的信息存储在cursor对象内。
    cursor.execute(select_sql)
#获取一条记录,每条记录做为一个tuple(元组)返回
data=cursor.fetchone()
print(data)
#获取2条记录,注意由于之前执行有了fetchone(),所以游标已经指到第二条记录了,也就是从第二条开始的2条记录
data=cursor.fetchmany(2)
print(data)
cursor.execute(select_sql)
#获取所有结果
data=cursor.fetchall()
print(data)
cursor.execute(select_sql)
#获取所有结果
for (id, name, age) in cursor:
print("ID:{}  Name:{}  Age:{}".format(id, name, age))
except mysql.connector.Error as err:
print("query table 'mytable' failed.")
print("Error: {}".format(err.msg))
sys.exit()
connection.commit()
cursor.close()
connection.close()
  输出:
  (1, 'Jay', 22)
[(2, 'Tony', 26), (3, '邵', 24)]
[(1, 'Jay', 22), (2, 'Tony', 26), (3, '邵', 24)]
ID:1  Name:Jay  Age:22
ID:2  Name:Tony  Age:26
ID:3  Name:邵  Age:24
  
  

运维网声明 1、欢迎大家加入本站运维交流群:群②:261659950 群⑤:202807635 群⑦870801961 群⑧679858003
2、本站所有主题由该帖子作者发表,该帖子作者与运维网享有帖子相关版权
3、所有作品的著作权均归原作者享有,请您和我们一样尊重他人的著作权等合法权益。如果您对作品感到满意,请购买正版
4、禁止制作、复制、发布和传播具有反动、淫秽、色情、暴力、凶杀等内容的信息,一经发现立即删除。若您因此触犯法律,一切后果自负,我们对此不承担任何责任
5、所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其内容的准确性、可靠性、正当性、安全性、合法性等负责,亦不承担任何法律责任
6、所有作品仅供您个人学习、研究或欣赏,不得用于商业或者其他用途,否则,一切后果均由您自己承担,我们对此不承担任何法律责任
7、如涉及侵犯版权等问题,请您及时通知我们,我们将立即采取措施予以解决
8、联系人Email:admin@iyunv.com 网址:www.yunweiku.com

所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其承担任何法律责任,如涉及侵犯版权等问题,请您及时通知我们,我们将立即处理,联系人Email:kefu@iyunv.com,QQ:1061981298 本贴地址:https://www.yunweiku.com/thread-58615-1-1.html 上篇帖子: python开发_sqlite3_绝对完整_博主推荐 下篇帖子: python之sqlite3使用详解
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

扫码加入运维网微信交流群X

扫码加入运维网微信交流群

扫描二维码加入运维网微信交流群,最新一手资源尽在官方微信交流群!快快加入我们吧...

扫描微信二维码查看详情

客服E-mail:kefu@iyunv.com 客服QQ:1061981298


QQ群⑦:运维网交流群⑦ QQ群⑧:运维网交流群⑧ k8s群:运维网kubernetes交流群


提醒:禁止发布任何违反国家法律、法规的言论与图片等内容;本站内容均来自个人观点与网络等信息,非本站认同之观点.


本站大部分资源是网友从网上搜集分享而来,其版权均归原作者及其网站所有,我们尊重他人的合法权益,如有内容侵犯您的合法权益,请及时与我们联系进行核实删除!



合作伙伴: 青云cloud

快速回复 返回顶部 返回列表