python2.7中MySQLdb的安裝與使用詳解


Python2.7中MySQLdb的使用

import MySQLdb
#1.建立連接
connect = MySQLdb.connect(
						'127.0.0.1', #數據庫地址
						'root',      #數據庫用戶名
						'666666',	 #數據庫密碼
						'peewee',    #數據庫名
						 3306,       #數據庫端口(默認就是3306,端口不加引號,不然報錯)   
						charset='utf8' #設置字符集編碼
						)   
#2.實例化游標(是一個內存地址,存放的是python對mysql提交的命名和執行命令之后返回的結果)
cursor = connect.cursor()
#3.定義要執行sql語句(比如現在我們要創建一個teacher表)
sql = """create table if not exists teacher(
	id int primary key auto_increment,
	name char(20) not null,
	age char(3) not null,
	sex char(1) not null,
	email char(50) not null,
	address char(100) not null
	)"""
#4.提交命令
cursor.execute(sql) #通過execute()方法向mysql提交要執行的sql命令

#5.提交修改(將python提交給mysql的sql命令在mysql當中執行)
connect.commit()

#6.關閉游標(如果不關閉會占用內存資源)
cursor.close()

#7.關閉連接
connect.close()

#以上就是創建了一個teacher的表,去數據庫上面查看,可以看得到
mysql> desc teacher;
+---------+-------------+------+-----+---------+----------------+
| Field   | Type        | Null | Key | Default | Extra          |
+---------+-------------+------+-----+---------+----------------+
| id      | int(11)     | NO   | PRI | NULL    | auto_increment |
| name    | varchar(50) | NO   |     | NULL    |                |
| age     | int(11)     | NO   |     | NULL    |                |
| sex     | varchar(50) | NO   |     | NULL    |                |
| email   | varchar(50) | NO   |     | NULL    |                |
| address | varchar(50) | NO   |     | NULL    |                |
+---------+-------------+------+-----+---------+----------------+

當然,如果你要想刪除數據,改下sql語句就行

下面我們看看查看
connect = MySQLdb.connect(
						'127.0.0.1', #數據庫地址
						'root',      #數據庫用戶名
						'666666',	 #數據庫密碼
						'peewee',    #數據庫名
						 3306,       #數據庫端口(默認就是3306,端口不加引號,不然報錯)   
						charset='utf8' #設置字符集編碼
						)   

cursor = connect.cursor()

sql = "select * from teacher where name = 'json' order by age desc"
cursor.execute(sql) #通過execute()方法向mysql提交要執行的sql命令

connect.commit()

results = cursor.fetchall() #fetchall()方法獲取所有內容

for res in results:
name = res[1]
age = res[2]
sex = res[3]
email = res[4]
address = res[5]
print 'name:%s,age:%s,sex:%s,email:%s,address:%s'%(name,age,sex,email,address)

cursor.close()

connect.close()
可以看到結果
name:A,age:22,sex:男,email:123@qq.com,address:北京
name:B,age:20,sex:女,email:123@qq.com,address:天津南開

OK,MySQLdb就介紹到這里。歡迎吐槽~


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM