Python操作MySQL簡單實現(xiàn)方法
更新時間:2015年01月26日 11:58:58 投稿:shichen2014
這篇文章主要介紹了Python操作MySQL簡單實現(xiàn)方法,通過一個簡單的實例講述了Python針對mysql數(shù)據(jù)庫的增刪改查技巧,需要的朋友可以參考下
本文實例講述了Python操作MySQL簡單實現(xiàn)方法。分享給大家供大家參考。具體分析如下:
一、安裝:
安裝MySQL
安裝MySQL不用多說了,下載下來安裝就是,沒有特別需要注意的地方。
一個下載地址:點擊打開鏈接
二、示例:
復制代碼 代碼如下:
# coding=utf-8
import MySQLdb
#查詢數(shù)量
def Count(cur):
count=cur.execute('select * from Student')
print 'there has %s rows record' % count
#插入
def Insert(cur):
sql = "insert into Student(ID,Name,Age,Sex)values(%s,%s,%s,%s)"
param = (2,'xiaoming',24,'boy')
cur.execute(sql,param)
#查詢
def Select(cur):
n = cur.execute("select * from Student")
print "------"
for row in cur.fetchall():
for r in row:
print r
print "------"
#更新
def Update(cur):
sql = "update Student set Name = %s where ID = 2"
param = ("xiaoxue")
count = cur.execute(sql,param)
#刪除
def Delete(cur):
sql = "delete from Student where Name = %s"
param =("xiaoxue")
n = cur.execute(sql,param)
try:
conn=MySQLdb.connect(host='localhost',user='root',passwd='123456',db='python',port=3306)
cur=conn.cursor()
#數(shù)量
Count(cur)
#查詢
Select(cur)
#插入
Insert(cur)
print "插入之后"
#查詢
Select(cur)
#更新
Update(cur)
print "更新之后"
#查詢
Select(cur)
#刪除
Delete(cur)
print "刪除之后"
#查詢
Select(cur)
cur.close()
conn.close()
except MySQLdb.Error,e:
print "Mysql Error %d: %s" % (e.args[0], e.args[1])
import MySQLdb
#查詢數(shù)量
def Count(cur):
count=cur.execute('select * from Student')
print 'there has %s rows record' % count
#插入
def Insert(cur):
sql = "insert into Student(ID,Name,Age,Sex)values(%s,%s,%s,%s)"
param = (2,'xiaoming',24,'boy')
cur.execute(sql,param)
#查詢
def Select(cur):
n = cur.execute("select * from Student")
print "------"
for row in cur.fetchall():
for r in row:
print r
print "------"
#更新
def Update(cur):
sql = "update Student set Name = %s where ID = 2"
param = ("xiaoxue")
count = cur.execute(sql,param)
#刪除
def Delete(cur):
sql = "delete from Student where Name = %s"
param =("xiaoxue")
n = cur.execute(sql,param)
try:
conn=MySQLdb.connect(host='localhost',user='root',passwd='123456',db='python',port=3306)
cur=conn.cursor()
#數(shù)量
Count(cur)
#查詢
Select(cur)
#插入
Insert(cur)
print "插入之后"
#查詢
Select(cur)
#更新
Update(cur)
print "更新之后"
#查詢
Select(cur)
#刪除
Delete(cur)
print "刪除之后"
#查詢
Select(cur)
cur.close()
conn.close()
except MySQLdb.Error,e:
print "Mysql Error %d: %s" % (e.args[0], e.args[1])
希望本文所述對大家的Python程序設計有所幫助。
相關(guān)文章
Python實現(xiàn)提取和去除數(shù)據(jù)中包含關(guān)鍵詞的行
這篇文章主要介紹了Python如何提取數(shù)據(jù)中包含關(guān)鍵詞的行已經(jīng)如何去除數(shù)據(jù)中包含關(guān)鍵詞的行,文中的示例代碼講解詳細,需要的可以參考一下2023-08-08