您好,登錄后才能下訂單哦!
1.插入數(shù)據(jù)
import MySQLdb
#創(chuàng)建連接
conn = MySQLdb.connect(host='127.0.0.1',user='root',passwd='123456',db='test')
cur = conn.cursor()
# execute 執(zhí)行,%s形式是為了防止sql注入
reCount = cur.execute('insert INTO test1 (name,country,age,address) VALUES (%s,%s,%s,%s,%s)',('2','jerry','china','23','beijing'))
'''
#另一種寫法
sql = "insert INTO test1 (name,country,age,address) VALUES (%s,%s,%s,%s,%s)"
params = ('2','jerry','china','23','beijing')
reCount = cur.execute(sql,params)
'''
# 提交
conn.commit()
# 關(guān)閉連接
cur.close()
conn.close()
print reCount
2. 更新數(shù)據(jù)庫
import MySQLdb
# 創(chuàng)建連接
conn = MySQLdb.connect(host='127.0.0.1',user='root',passwd='123456',db='test')
cur = conn.cursor()
sql = "update test1 set address = %s where id = 2"
# 添加逗號表示是一個序列
params = ('BeiJing',)
reCount = cur.execute(sql,params)
# 提交
conn.commit()
# 關(guān)閉連接
cur.close()
conn.close()
print reCount
3. 查找數(shù)據(jù)
import MySQLdb
# 創(chuàng)建連接
conn = MySQLdb.connect(host='127.0.0.1',user='root',passwd='123456',db='test')
cur = conn.cursor()
sql = "select * FROM test1 "
reCount = cur.execute(sql)
#顯示查找到的數(shù)據(jù),結(jié)果以字典形式展示
print cur.fetchall()
# 關(guān)閉連接cur.close()
conn.close()
print reCount
4. 刪除數(shù)據(jù)
import MySQLdb
# 創(chuàng)建連接
conn = MySQLdb.connect(host='127.0.0.1',user='root',passwd='123456',db='test')
cur = conn.cursor()
sql = "delete FROM test1 WHERE id = 2"
reCount = cur.execute(sql)
# 提交
conn.commit()
# 關(guān)閉連接
cur.close()
conn.close()
print reCount
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。