數據庫python,python數據庫操作常用功能使用詳解(創建表/插入數據/獲取數據)

 2023-10-21 阅读 32 评论 0

摘要:實例1、取得MYSQL版本 # -*- coding: UTF-8 -*- #安裝MYSQL DB for python import MySQLdb as mdb con = None try:#連接mysql的方法:connect(host='localhost',user='root',passwd='root',db='test',port=33

實例1、取得MYSQL版本

# -*- coding: UTF-8 -*-
#安裝MYSQL DB for python
import MySQLdb as mdb
con = None
try:#連接mysql的方法:connect(host='localhost',user='root',passwd='root',db='test',port=3306)con = mdb.connect('localhost', 'root','root', 'test');#所有的查詢,都在連接con的一個模塊cursor上面運行的cur = con.cursor()#執行一個查詢cur.execute("SELECT VERSION()")#取得上個查詢的結果,是單個結果data = cur.fetchone()print "Database version : %s " % data
finally:if con:#無論如何,連接記得關閉con.close()

執行結果:

數據庫python?Database version : 5.5.25

?

?

python做數據庫、實例2、創建一個表并且插入數據

# -*- coding: UTF-8 -*-
import MySQLdb as mdb
import sys
#將con設定為全局連接
con = mdb.connect('localhost', 'root', 'root', 'test');
with con:#獲取連接的cursor,只有獲取了cursor,我們才能進行各種操作cur = con.cursor()#創建一個數據表 writers(id,name)cur.execute("CREATE TABLE IF NOT EXISTS \Writers(Id INT PRIMARY KEY AUTO_INCREMENT, Name VARCHAR(25))")#以下插入了5條數據cur.execute("INSERT INTO Writers(Name) VALUES('Jack London')")cur.execute("INSERT INTO Writers(Name) VALUES('Honore de Balzac')")cur.execute("INSERT INTO Writers(Name) VALUES('Lion Feuchtwanger')")cur.execute("INSERT INTO Writers(Name) VALUES('Emile Zola')")cur.execute("INSERT INTO Writers(Name) VALUES('Truman Capote')")

?實例3、拼接插入SQL數據

 1 import MySQLdb
 2 conn = MySQLdb.connect(host='127.0.0.1',user='root',passwd='123456',db='test2',)
 3 cur = conn.cursor()
 4 sql = "insert into admin (name,addres) values (%s,%s)" 
 5 params = ('zhang','san')
 6 #sql = "insert into table(key1,key2,key3) values (%s,%s,%s)"%(value1,value2,value3)
 7 temp=cur.execute(sql,params)
 8 conn.commit()
 9 recount = cur.execute('select *from admin')
10 rows = cur.fetchall()
11 
12 cur.close()
13 conn.close()
14 for time in rows:
15  #print temp #查看影響條目
16  #print rows #查看數據庫表內容
17  print time  
View Code

結果:

python編程入門?(1L, 'hejin', 'USA')
(2L, 'jctang', 'usa')
(5L, 'zhang', 'san')

?

實例4、python使用slect獲取mysql的數據并遍歷

# -*- coding: UTF-8 -*-
import MySQLdb as mdb
import sys
#連接mysql,獲取連接的對象
con = mdb.connect('localhost', 'root', 'root', 'test');
with con:#仍然是,第一步要獲取連接的cursor對象,用于執行查詢cur = con.cursor()#類似于其他語言的query函數,execute是python中的執行查詢函數cur.execute("SELECT * FROM Writers")#使用fetchall函數,將結果集(多維元組)存入rows里面rows = cur.fetchall()#依次遍歷結果集,發現每個元素,就是表中的一條記錄,用一個元組來顯示for row in rows:print row
執行結果:
(1L, ‘Jack London')
(2L, ‘Honore de Balzac')
(3L, ‘Lion Feuchtwanger')
(4L, ‘Emile Zola')
(5L, ‘Truman Capote')

python元祖、?

實例5、使用字典cursor取得結果集(可以使用表字段名字訪問值)

import MySQLdb as mdb
import sys
#獲得mysql查詢的鏈接對象
con = mdb.connect('localhost', 'root', '123456', 'test2')
with con:
#獲取連接上的字典cursor,注意獲取的方法,
#每一個cursor其實都是cursor的子類
cur = con.cursor(mdb.cursors.DictCursor)
#執行語句不變
cur.execute("select *from admin")
#獲取數據方法不變
rows = cur.fetchall()
#遍歷數據也不變(比上一個更直接一點)
for row in rows:
#這里,可以使用鍵值對的方法,由鍵名字來獲取數據print '%s %s %s' %(row['id'],row['name'],row['addres'])
View Code

?

?結果:

10 zhang san
11 zhang san
12 zhang san
13 zhang san
14 zhang san
15 zhang san

? ? ??

?

實例6、獲取單個表的字段名和信息的方法


# -*- coding: UTF-8 -*-
import MySQLdb as mdb
import sys
#獲取數據庫的鏈接對象
con = mdb.connect('localhost', 'root', 'root', 'test')
with con:#獲取普通的查詢cursorcur = con.cursor()cur.execute("SELECT * FROM Writers")rows = cur.fetchall()#獲取連接對象的描述信息desc = cur.descriptionprint 'cur.description:',desc#打印表頭,就是字段名字print "%s %3s" % (desc[0][0], desc[1][0])for row in rows:#打印結果print "%2s %3s" % row
運行結果: cur.description: ((‘Id', 3, 1, 11, 11, 0, 0), (‘Name', 253, 17, 25, 25, 0, 1))
Id Name
1 Jack London
2 Honore de Balzac
3 Lion Feuchtwanger
4 Emile Zola
5 Truman Capote

?


實例7、使用Prepared statements執行查詢(更安全方便)

?

# -*- coding: UTF-8 -*-
import MySQLdb as mdb
import sys
con = mdb.connect('localhost', 'root', 'root', 'test')
with con:cur = con.cursor()#我們看到,這里可以通過寫一個可以組裝的sql語句來進行cur.execute("UPDATE Writers SET Name = %s WHERE Id = %s",("Guy de Maupasant", "4"))#使用cur.rowcount獲取影響了多少行print "Number of rows updated: %d" % cur.rowcount

結果:

Number of rows updated: 1?
實例 8 刪除某一列SQL數據
import MySQLdb
conn = MySQLdb.connect(host='127.0.0.1',user='root',passwd='123456',db='test2',)
cur = conn.cursor()
sql = "delete from admin where id=%s"
params = ('2')
cur.execute(sql,params)
conn.commit()
cur.close()
conn.close()
View Code

?

轉載于:https://www.cnblogs.com/name/p/4914515.html

版权声明:本站所有资料均为网友推荐收集整理而来,仅供学习和研究交流使用。

原文链接:https://hbdhgg.com/3/155624.html

发表评论:

本站为非赢利网站,部分文章来源或改编自互联网及其他公众平台,主要目的在于分享信息,版权归原作者所有,内容仅供读者参考,如有侵权请联系我们删除!

Copyright © 2022 匯編語言學習筆記 Inc. 保留所有权利。

底部版权信息