Python和MySQL資料庫簡單操作
資料庫分類
-
SQL(關係型資料庫)
- MySQL
- Oracle
- SQL Server
- DB2
-
NoSQL
這個NoSQL表示是Not Only SQL,而不是No SQL。SQL的本質是保證事物的完整性(高併發的情況下)遵循ACID?,無法水平擴充套件。因而NoSQL基於CAP,在犧牲事物(有可能丟失)的情況下實行水平擴充套件,- MongoDB
- Neo4j
- HBase
MySQL的簡單操作
- 使用Navicat來建立表
-
使用Python來操作SQL
-
首先使用開發包,主要有三種
mysql-connector
、MySQLdb
、SQLAlchemy
。其中相比mysql-connector
,MySQLdb
用的比較多。而第一個則是官方給出的方案。 -
安裝方案如下:
pip3 install mysql-connector#安裝mysql-connector pip3 install PyMySQL#安裝MySQLdb 3.x以上的替代方案
-
首先使用開發包,主要有三種
mysql-connector實操
-
建立連結
from mysql import connector conn = connector.connect(host = 'localhost', port = 3306 , user = 'root', password = 'laoduan2008', charset = 'utf8') conn.autocommit = True #為了不重複輸入commit
ERROR Record:-
mysql.connector.errors.NotSupportedError: Authentication plugin 'caching_sha2_password' is not supported
MySQL8在這裡和低版本不相容 ,你可以重新安裝MySQL(或者用Reconfigure選項),把認證的選項設定為“Use Legacy Authentication Method”, 或者你如果不是必須要用MySQL 8,可以降級到低版本。
-
-
建立遊標
cursor = conn.cursor() sqltext = 'insert into users(name, address, email) values ("deamov","beijing","abc@blabla")' #設定語句 text_temple = 'insert into users(name, address, email) values (%s ,%s ,%s)' cursor.executemany(sql_template,userinfo) #如何執行多條語句
-
執行SQL
cursor.execute(sqltext) #執行語句
-
關閉連線
cursor.close() conn.close()
PyMySQL
-
建立連結
import pymysql conn = pymysql.connect() conn.autocommit(True)
ERROR Record-
pymysql.err.OperationalError: (1045, "Access denied for user 'root'@'localhost' (using password: NO)")
有可能是root賬號的密碼這些不能登陸,通過root賬號登陸後,分配一個賬號類似CREATE USER 'deamov'@'localhost IDENTIFIED WITH mysql_native_password BY 'password';
。之後,use your_database_name
選擇了你要用的資料庫後,將許可權給你的新的賬戶grant all privileges on *.* to deamov@localhost
。
-
-
建立遊標
cursor = conn.cursor() #mysql-connector用的是弱引用 #PyMySQL的遊標可以在函式裡用
-
執行SQL
sqltext = 'select * from users' cursor.excute(sqltext) for row in cursor: print row #讀取所有的 for row in cursor.fetchmany(2): print row #讀取兩條 from faker import Factory userfaker = Factory.create() userinfo = [(userfaker.name(),userfaker.address(),userfaker.email()) for i in range(10)] text_temple = 'insert into users(name, address, email) values (%s ,%s ,%s) cursor.executemany(sql_template,userinfo) #批量插入
-
關閉連結
cursor.close() conn.close()
SQLAlchemy
The Python SQL Toolkit and Object Relational Mapper。
ORM(O是面向物件,R是面向關係,M是Map):
面向物件和麵向關係的模擬關聯。
-
表對映到類
- 行對映到物件
- 列對映到屬性
優點如下
- 隱藏資料庫實現
- 良好的資料庫操作介面,簡單,學習成本低。
- 動態資料表對映
開發步驟
-
建立連結
from sqlalchemy import create_engine from sqlalchemy.ext.declarative import declarative_base from sqlalchemy import Column,Integer,String,DateTime,ForeignKey engine = create_engine('mysql+mysqldb://deamov:[email protected]:3306/MySQLTest?charset=utf8',echo=True) #echo這個引數是把sql的語句打印出來
-
建立對映(表的設計)
Base = declarative_base() class User(Base): __tablename__ = 'users' id = Column(Integer, primary_key = Ture) name = Column(String(40)) orders = relationship('Order') class Product(Base): __tablename__ = 'products' id = Column(Integer, primary_key = Ture) name = Column(String(40)) orders = relationship('Order') #這個orders不是ddl語言,而是針對面向物件程式設計而言的 class Order(Base): __tablename__ = 'orders' id = Column(Integer,primary_key = True) otime = Column(DateTime) uid = Column(Integer, ForeignKey('users.id')) pid = Column(Integer, ForeignKey('products.id')) #定義外來鍵
-
初始化對映例項
Base.metadata.create_all(engine)
-
建立會話
Session = sessionmaker(engine) session = Session()
-
持久化物件例項
DeamoV = User(name = 'DeamoV') session.add(DeamoV) p1 = Product(name = 'p1') session.add(p1) session.commit() ''' ------ ''' #DeamoV = session.query(User).filter(User.name=='DeamoV') #返回的是一個集合,集合裡是選擇的例項類 #p1 = session.query(Product).filter(Product.name=='p1') #這裡的Product和User都是類的名字 o1 = Order(uid=p1.id ,pid=p1.id) #添加了一個關係 session.add(o1) orders=DeamoV.orders #這個時候獲取這個關係,目前只有一個關係 for order in orders: print(order.id)