1.插入數(shù)據(jù)
站在用戶的角度思考問題,與客戶深入溝通,找到茅箭網(wǎng)站設(shè)計(jì)與茅箭網(wǎng)站推廣的解決方案,憑借多年的經(jīng)驗(yàn),讓設(shè)計(jì)與互聯(lián)網(wǎng)技術(shù)結(jié)合,創(chuàng)造個(gè)性化、用戶體驗(yàn)好的作品,建站類型包括:成都網(wǎng)站設(shè)計(jì)、成都網(wǎng)站制作、企業(yè)官網(wǎng)、英文網(wǎng)站、手機(jī)端網(wǎng)站、網(wǎng)站推廣、空間域名、網(wǎng)絡(luò)空間、企業(yè)郵箱。業(yè)務(wù)覆蓋茅箭地區(qū)。
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"
# 添加逗號(hào)表示是一個(gè)序列
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