pymysql 的使用流程:
1. 建立資料庫連線
物件名(一般用db)=pymysql.connect("主機位址","使用者名稱","密碼","庫名",charset=utf8)建立游標物件:
connect物件(db)的方法:
cursor()#建立乙個游標物件db.cursor()commit()#提交到資料庫rollback()#回滾使用游標物件的方法和sql語句操控mysql資料庫:
execute()#執行sql命令fetchone() #取得結果集的第一條記錄fetchmany(數字)#取得結果集的 幾條 記錄fetchall() # 取得結果集的所有行close() 關閉游標物件提交commit
db.commit()關閉游標
cur.close()關閉資料庫連線
db.close()
例項:import pymysql
#開啟資料庫連線
db=pymysql.connect("localhost","root","130130",charset="utf8")
#建立乙個游標物件
cur=db.cursor()
#建立庫python
cur.execute("create database if not exists\
python;")
#切換庫
cur.execute("use python;")
#建立表t1
cur.execute("create table if not exists t1(\
id int primary key,\
name varchar(20),\
score tinyint unsigned);")
#在t1中插入5條記錄
cur.execute("insert into t1 values\
(1,'貂蟬',88),\
(2,'趙雲',100),\
(3,'諸葛',80),\
(4,'張飛',60),\
(5,'司馬懿',99);")
#提交到資料庫
db.commit()
#關閉游標
cur.close()
#關閉資料庫連線
db.close()
MySQL 五 (MySQL與Python互動)
from pymysql import conn connect 引數列表 物件的方法cs1 conn.cursor 物件的方法 物件的屬性 from pymysql import def main 建立connection連線 conn connect host localhost port 33...
mysql與python的互動
conn connect 引數列表 cursor1 conn.cursor mode表示移動的方式 mode的預設值為relative,表示基於當前行移動到value,value為正則向下移動,value為負則向上移動 mode的值為absolute,表示基於第一條資料的位置,第一條資料位置為零 建...
python與MySQL的互動
要想和mysql資料庫互動,首先需要安裝資料庫驅動模組,python2和python3的資料庫驅動是不同的。python2中的資料庫模組是mysqldb,可以通過以下命令安裝 sudo apt get install python mysql在檔案中引入模組 import mysqldbpython...