Python操作Mysql數(shù)據(jù)庫(kù)

連接數(shù)據(jù)庫(kù)

import pymysql

db = pymysql.connect(host='localhost',user='root', password='123456', port=3306)
cursor = db.cursor()
cursor.execute('SELECT VERSION()')
data = cursor.fetchone()
print('Database version:', data)
db.close()

創(chuàng)建數(shù)據(jù)庫(kù)

import pymysql

db = pymysql.connect(host='localhost',user='root', password='root', port=3306)
cursor = db.cursor()
cursor.execute("CREATE DATABASE demo DEFAULT CHARACTER SET utf8")
db.close()

創(chuàng)建表

import pymysql

db = pymysql.connect(host='localhost', user='root', password='123456', port=3306, db='demo')
cursor = db.cursor()
sql = 'CREATE TABLE IF NOT EXISTS students (id VARCHAR(255) NOT NULL, name VARCHAR(255) NOT NULL, age INT NOT NULL, PRIMARY KEY (id))'
cursor.execute(sql)
db.close()

插入數(shù)據(jù)

import pymysql

id = '10'
name = 'zhang'
age = 18

db = pymysql.connect(host='localhost', user='root', password='root', port=3306, db='demo')
cursor = db.cursor()
sql = 'INSERT INTO students(id, name, age) values(%s, %s, %s)'
try:
    cursor.execute(sql, (id, name, age))
    db.commit()
except:
    db.rollback()
db.close()

事務(wù)機(jī)制,一旦出錯(cuò)會(huì)回滾,不存在一半插入一半沒(méi)插入的情況。

更新數(shù)據(jù)

sql = 'UPDATE students SET age = %s WHERE name = %s'
try:
   cursor.execute(sql, (30, 'zhang'))
   db.commit()
except:
   db.rollback()
db.close()

刪除數(shù)據(jù)

table = 'demo'
condition = 'age > 20'

sql = 'DELETE FROM  {table} WHERE {condition}'.format(table=table, condition=condition)
try:
    cursor.execute(sql)
    db.commit()
except:
    db.rollback()

db.close()

查詢數(shù)據(jù)

sql = 'SELECT * FROM students WHERE age >= 20'
try:
    cursor.execute(sql)
    print('Count:', cursor.rowcount)
    row = cursor.fetchone()
    while row:
        print('Row:', row)
        row = cursor.fetchone()
except:
    print('Error')

fetch()存在指針偏移的問(wèn)題,使用一次,指針就會(huì)向后偏移一次。

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容