除錯環境python3.6,除錯python操作mysql資料庫
python3.6下程式碼如下
#coding:utf-8
#python3.6使用pymysql操作mysql
print("=====================mysql資料庫=====================")
import pymysql.cursors
# 連線資料庫
connect = pymysql.Connect(
host='127.0.0.1',
port=3306,
user='root',
passwd='19910101a',
db='note',
charset='utf8'
)
# 獲取遊標
cursor = connect.cursor()
#刪除表
sql = 'DROP TABLE IF EXISTS student'
cursor.execute(sql)
connect.commit()
print('如果存在表就刪除表格')
#建立表格
sql = "CREATE TABLE student(id INTEGER PRIMARY KEY,name TEXT)"
try:
cursor.execute(sql)
connect.commit()
except:
print("表已存在")
print('成功建立表格')
# 插入資料
sql = "INSERT INTO student VALUES(%d,'%s')"
data = (1, 'student1')
cursor.execute(sql % data)
connect.commit()
print('成功插入', cursor.rowcount, '條資料')
# 修改資料
sql = "UPDATE student SET name = '%s' WHERE id = %d "
data = ('student2', 1)
cursor.execute(sql % data)
connect.commit()
print('成功修改', cursor.rowcount, '條資料')
# 查詢資料
sql = "SELECT * FROM student WHERE id=%d"
data = (1,)
cursor.execute(sql % data)
for row in cursor.fetchall():
print("%s" % str(row))
print('共查找出', cursor.rowcount, '條資料')
# 刪除資料
sql = "DELETE FROM student WHERE id = %d LIMIT %d"
data = (1, 1)
cursor.execute(sql % data)
connect.commit()
print('成功刪除', cursor.rowcount, '條資料')
# 事務處理
sql_1 = "UPDATE student SET name = name + '1' WHERE id = 1 "
try:
cursor.execute(sql_1)
except Exception as e:
connect.rollback() # 事務回滾
print('事務處理失敗', e)
else:
connect.commit() # 事務提交
print('事務處理成功', cursor.rowcount)
# 關閉連線
cursor.close()
connect.close()
#pymysql.Connect()引數說明
#host(str): MySQL伺服器地址
#port(int): MySQL伺服器埠號
#user(str): 使用者名稱
#passwd(str): 密碼
#db(str): 資料庫名稱
#charset(str): 連線編碼
#
#connection物件支援的方法
#cursor() 使用該連線建立並返回遊標
#commit() 提交當前事務
#rollback() 回滾當前事務
#close() 關閉連線
#
#cursor物件支援的方法
#execute(op) 執行一個數據庫的查詢命令
#fetchone() 取得結果集的下一行
#fetchmany(size) 獲取結果集的下幾行
#fetchall() 獲取結果集中的所有行
#rowcount() 返回資料條數或影響行數
#close() 關閉遊標物件
python2.7下程式碼如下
如果連線失敗會報錯。
#coding:utf-8
#python2.7使用MySQLdb操作mysql
import MySQLdb
print("=====================mysql資料庫=====================")
getRC = lambda cur: cur.rowcount if hasattr(cur, 'rowcount') else -1 #獲取遊標所指向是資料的行數
HOST = "127.0.0.1" #資料庫主機
USER = 'root' #使用者名稱
PASSWORD = '111111' #密碼
DBNAME = 'note' #資料名稱
try:
conn = MySQLdb.connect(HOST,USER,PASSWORD,DBNAME) #連線mysql資料庫,引數:主機號、使用者名稱、密碼、資料庫
curs=conn.cursor() # 獲取遊標
curs.execute('CREATE TABLE student(id INTEGER PRIMARY KEY,name TEXT)') # 執行程式碼,建立表和欄位
curs.execute("INSERT INTO student VALUES(1,'student1')"); # 新增記錄
curs.execute("INSERT INTO student VALUES(%d, '%s')" % (2, 'student2')) #新增記錄
conn.commit() # 每次執行完後都應該儲存
except Exception:print("資料表和記錄已經新增")
finally:
curs.execute("UPDATE student SET name='student3' WHERE id=2") #更新記錄
curs.execute("SELECT * FROM student") # 查詢記錄
for row in curs.fetchall():
print(row[0],row[1])
curs.execute('DELETE FROM student WHERE id=%d' % 1) #刪除記錄
curs.execute('DROP TABLE student') #刪除表
curs.close() #關閉遊標
conn.close() #關閉連線
原文:https://blog.csdn.net/luanpeng825485697/article/details/77816801