您好,登錄后才能下訂單哦!
1.插入數據
import MySQLdb
#創建連接
conn = MySQLdb.connect(host='127.0.0.1',user='root',passwd='123456',db='test')
cur = conn.cursor()
# execute 執行,%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()
# 關閉連接
cur.close()
conn.close()
print reCount
2. 更新數據庫
import MySQLdb
# 創建連接
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()
# 關閉連接
cur.close()
conn.close()
print reCount
3. 查找數據
import MySQLdb
# 創建連接
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)
#顯示查找到的數據,結果以字典形式展示
print cur.fetchall()
# 關閉連接cur.close()
conn.close()
print reCount
4. 刪除數據
import MySQLdb
# 創建連接
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()
# 關閉連接
cur.close()
conn.close()
print reCount
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。