Python - MySQL數據庫相關對象及優化操作

Python數據庫的Connection、Cursor兩大對象

Python數據庫圖解流程
在這裏插入圖片描述
在這裏插入圖片描述


參數優化

url
在url後加上參數rewriteBatchedStatements=true表示MySQL服務開啓批次寫入,此參數是批次寫入的一個比較重要參數,可明顯提升性能
batchsize
DataFrame writer批次寫入MySQL的條數,也爲提升性能的參數
isolationLevel
事務隔離級別,DataFrame寫入不需要開啓事務,爲None
truncate
overwrite模式時可用,表示在覆蓋原始數據的時候不會刪除表結構而是複用


Another

Python實現Java中的PrepareStatement功能

# import MySQL module
import MySQLdb
# get user input
name = raw_input("Please enter a name: ")
species = raw_input("Please enter a species: ")
# connect
db = MySQLdb.connect(host="localhost", user="joe", passwd="secret",db="db56a")
# create a cursor
cursor = db.cursor()
# execute SQL statement
cursor.execute("INSERT INTO animals (name, species) VALUES (%s, %s)",(name, species))
# import MySQL module
import MySQLdb
# connect
db = MySQLdb.connect(host="localhost", user="joe", passwd="secret",db="db56a")
# create a cursor
cursor = db.cursor()
# execute SQL statement
cursor.execute("""INSERT INTO test (field1, field2) VALUES ("val1","val2")""")
# get ID of last inserted record
print "ID of inserted record is ", int(cursor.insert_id())
# import MySQL module
import MySQLdb
# connect
db = MySQLdb.connect(host="localhost", user="joe", passwd="secret",db="db56a")
# create a cursor
cursor = db.cursor()
# dynamically generate SQL statements from  list
cursor.executemany("INSERT
INTO animals (name, species) VALUES (%s,%s)", [('Rollo', 'Rat'), 
('Dudley', 'Dolphin'),  ('Mark', 'Marmoset')])
# import MySQL module
import MySQLdb
# initialize some variables
name = ""
data = []
# loop and ask for user input
while (1):
name = raw_input("Please enter a name (EOF to end): ")
if name == "EOF":
break
species = raw_input("Please enter a species: ")
# put user input into a tuple
tuple = (name, species)
# and append to data[] list
data.append(tuple)
# connect
db = MySQLdb.connect(host="localhost", user="joe", passwd="secret",db="db56a")
# create a cursor
cursor = db.cursor()
# dynamically generate SQL statements from data[] list
cursor.executemany("INSERT INTO animals (name, species) VALUES (%s,%s)",data) 
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章