import pymysql
# connect = pymysql.connect(host='localhost')
connect = pymysql.connect(host='127.0.0.1', port =3309, user ='root',
passwd ='root', db ='bwdb', charset ='utf8')# 创建游标,指针指向数据库的开始
cursor = connect.cursor()# 通过游标去运行SQL,最终要关闭try:# rows = cursor.execute("create table if not exists t_temp(a varchar(10))")# 每1000次提交一次for i inrange(1000):
rows = cursor.execute("insert into t_temp values('aaaa%s')"%str(i +1))# 提交
connect.commit()
executeSelect = cursor.execute("select * from t_temp")
connect.commit()# fetchone = cursor.fetchone()
fetchall = cursor.fetchall()print(fetchall)
connect.commit()except pymysql.err.ProgrammingError as e:print("链接错误")print(e)
connect.rollback()else:print("插入"+str(rows))print("查询"+str(executeSelect))
cursor.close()print(type(connect), connect)
connect.close()
Python:数据库MongoDB连接
(1)简单连接
from pymongo import MongoClient
import pymongo
client = MongoClient("127.0.0.1",27017)
db = client.database180929
myset:pymongo.collection.Collection = db.student
for data in myset.find():print(data)
client.close()
(2)增删查改
from pymongo import MongoClient
import pymongo
client = MongoClient("127.0.0.1",27017)
db = client.database180929
myset:pymongo.collection.Collection = db.student
# 插入
one = myset.insert_one({"name":"haha","age":19})print(one, one.inserted_id, one.acknowledged)
many = myset.insert_many([{"name":"lisi","age":20},{"name":"lisi","age":23}])print(many, many.inserted_ids, one.acknowledged)# 修改
update_one = myset.update_one({"name":"lisi"},{"$set":{"name":"lisa"}})print(update_one.acknowledged, update_one.raw_result, update_one.modified_count, update_one.upserted_id)
update_many = myset.update_many({"name":"lisia"},{"$set":{"name":"lisia"}})print(update_many.modified_count, update_many.matched_count, update_many.upserted_id, update_many.acknowledged, update_many.raw_result)# 删除
delete_one = myset.delete_one({"name":"lisi"})print(delete_one.raw_result)# myset.delete_many()
datas = myset.find()for data in datas:print(data)
client.close()