python入门之数据库操作

1、目前主流的数据库有两种,

  • 一个是关系型数据库,如MySql
  • 一个是非关系型数据库 如mongodb

对与mysql和mongodb数据库,python中分别有对接的连接操作库

2、python连接mysql:
在python中,连接mysql用到的库是

pymysql

安装方法直接使用命令:

pip install pymsql

引入方式:

import pymysql

连接数据库:

db = pymysql.connect(host='127.0.0.1',
                     user='root',
                     password='123456',
                     database='bookmanager')

获取游标:

cur = db.cursor()

关闭数据库:

db.close()

使用python执行增删改查的操作的完整代码:

#!/usr/bin/python3
 
import pymysql
 
db = pymysql.connect(host='127.0.0.1',
                     user='root',
                     password='123456',
                     database='bookmanager')
#print(db)
cur = db.cursor()
#print(cur)

# SQL 插入语句
sql = """INSERT INTO BOOK(NAME,
         AUTHOR, PUBLISH, HAVE, HOT)
         VALUES ('001', 'test', '002', 100, 200)"""
# 查询
sql = "SELECT * FROM BOOK WHERE hot > 1000"

#修改
sql = "UPDATE BOOK SET name = 'ZS1000' WHERE hot > 1000"

#删除
sql = "delete FROM BOOK where  hot > 1000"

sql = """CREATE TABLE TEST (
         FIRST_NAME  CHAR(20) NOT NULL,
         LAST_NAME  CHAR(20),
         AGE INT,  
         SEX CHAR(1),
         INCOME FLOAT )"""
#删除表
sql = "DROP TABLE IF EXISTS TEST"



try:
    cur.execute(sql)
    db.commit()
except:
    print('have exception')
    db.rollback()

db.close()

3、python连接mongodb的库是:

pymongo

安装以及引人:

pip install pymongo
import pymongo

建立数据库连接:

mongo_client = pymongo.MongoClient(“mongodb://192.168.1.200:30000”)

指定数据库:

mongo_db = mongo_client[“test”]

操作数据库 完整代码如下:

#!/usr/bin/python3
 
import pymongo

mongo_client =  pymongo.MongoClient("mongodb://192.168.1.200:30000")

print(mongo_client)

mongo_db = mongo_client["test"]

print(mongo_db)

#获取集合
collist = mongo_db.list_collection_names()

#print(collist)

coll = mongo_db['new_coll']
#print(coll)
#coll.insert_one({'name':'new_coll'})
#获取集合
#collist = mongo_db.list_collection_names()
#print(collist)

coll = mongo_db["new_coll"]

for x in coll.find():
    print(x)

#query_my = {"name":"new_coll"}
#update_q = {"$set":{"name":"new_coll_1"}}

#coll.update_one(query_my,update_q)
#print(coll.find()[0])
print('*'*25)
query_my = {"name":"new_coll"}
coll.delete_many(query_my)

for x in coll.find():
    print(x)


你可能感兴趣的:(python基础技能,python实用,python,数据库,mysql,mongodb,入门)