python使用mysql數(shù)據(jù)庫(kù)示例代碼
一,安裝mysql
如果是windows 用戶(hù),mysql 的安裝非常簡(jiǎn)單,直接下載安裝文件,雙擊安裝文件一步一步進(jìn)行操作即可。
Linux 下的安裝可能會(huì)更加簡(jiǎn)單,除了下載安裝包進(jìn)行安裝外,一般的linux 倉(cāng)庫(kù)中都會(huì)有mysql ,我們只需要通過(guò)一個(gè)命令就可以下載安裝:
Ubuntu\deepin
>>sudo apt-get install mysql-server >>Sudo apt-get install mysql-client
centOS/redhat
>>yum install mysql
二,安裝MySQL-python
要想使python可以操作mysql 就需要MySQL-python驅(qū)動(dòng),它是python 操作mysql必不可少的模塊。
下載地址:https://pypi.python.org/pypi/MySQL-python/
下載MySQL-python-1.2.5.zip 文件之后直接解壓。進(jìn)入MySQL-python-1.2.5目錄:
>>python setup.py install
三,測(cè)試
測(cè)試非常簡(jiǎn)單,檢查MySQLdb 模塊是否可以正常導(dǎo)入。
fnngj@fnngj-H24X:~/pyse$ python Python 2.7.4 (default, Sep 26 2013, 03:20:56) [GCC 4.7.3] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import MySQLdb
沒(méi)有報(bào)錯(cuò)提示MySQLdb模塊找不到,說(shuō)明安裝OK ,下面開(kāi)始使用python 操作數(shù)據(jù)庫(kù)之前,我們有必要來(lái)回顧一下mysql的基本操作:
四,mysql 的基本操作
$ mysql -u root -p (有密碼時(shí)) $ mysql -u root (無(wú)密碼時(shí))
mysql> show databases; // 查看當(dāng)前所有的數(shù)據(jù)庫(kù)
+--------------------+
| Database |
+--------------------+
| information_schema |
| csvt |
| csvt04 |
| mysql |
| performance_schema |
| test |
+--------------------+
6 rows in set (0.18 sec)
mysql> use test; //作用與test數(shù)據(jù)庫(kù)
Database changed
mysql> show tables; //查看test庫(kù)下面的表
Empty set (0.00 sec)
//創(chuàng)建user表,name 和password 兩個(gè)字段
mysql> CREATE TABLE user (name VARCHAR(20),password VARCHAR(20)); Query OK, 0 rows affected (0.27 sec)
//向user表內(nèi)插入若干條數(shù)據(jù)
mysql> insert into user values('Tom','1321');
Query OK, 1 row affected (0.05 sec)
mysql> insert into user values('Alen','7875');
Query OK, 1 row affected (0.08 sec)
mysql> insert into user values('Jack','7455');
Query OK, 1 row affected (0.04 sec)
//查看user表的數(shù)據(jù)
mysql> select * from user;
+------+----------+
| name | password |
+------+----------+
| Tom | 1321 |
| Alen | 7875 |
| Jack | 7455 |
+------+----------+
3 rows in set (0.01 sec)
//刪除name 等于Jack的數(shù)據(jù)
mysql> delete from user where name = 'Jack';
Query OK, 1 rows affected (0.06 sec)
//修改name等于Alen 的password 為 1111
mysql> update user set password='1111' where name = 'Alen';
Query OK, 1 row affected (0.05 sec)
Rows matched: 1 Changed: 1 Warnings: 0
//查看表內(nèi)容
mysql> select * from user;
+--------+----------+
| name | password |
+--------+----------+
| Tom | 1321 |
| Alen | 1111 |
+--------+----------+
3 rows in set (0.00 sec)
五,python 操作mysql數(shù)據(jù)庫(kù)基礎(chǔ)
#coding=utf-8
import MySQLdb
conn= MySQLdb.connect(
host='localhost',
port = 3306,
user='root',
passwd='123456',
db ='test',
)
cur = conn.cursor()
#創(chuàng)建數(shù)據(jù)表
#cur.execute("create table student(id int ,name varchar(20),class varchar(30),age varchar(10))")
#插入一條數(shù)據(jù)
#cur.execute("insert into student values('2','Tom','3 year 2 class','9')")
#修改查詢(xún)條件的數(shù)據(jù)
#cur.execute("update student set class='3 year 1 class' where name = 'Tom'")
#刪除查詢(xún)條件的數(shù)據(jù)
#cur.execute("delete from student where age='9'")
cur.close()
conn.commit()
conn.close()
>>> conn = MySQLdb.connect(host='localhost',port = 3306,user='root', passwd='123456',db ='test',)
Connect() 方法用于創(chuàng)建數(shù)據(jù)庫(kù)的連接,里面可以指定參數(shù):用戶(hù)名,密碼,主機(jī)等信息。
這只是連接到了數(shù)據(jù)庫(kù),要想操作數(shù)據(jù)庫(kù)需要?jiǎng)?chuàng)建游標(biāo)。
>>> cur = conn.cursor()
通過(guò)獲取到的數(shù)據(jù)庫(kù)連接conn下的cursor()方法來(lái)創(chuàng)建游標(biāo)。
>>> cur.execute("create table student(id int ,name varchar(20),class varchar(30),age varchar(10))")
通過(guò)游標(biāo)cur 操作execute()方法可以寫(xiě)入純sql語(yǔ)句。通過(guò)execute()方法中寫(xiě)如sql語(yǔ)句來(lái)對(duì)數(shù)據(jù)進(jìn)行操作。
>>>cur.close()
cur.close() 關(guān)閉游標(biāo)
>>>conn.commit()
conn.commit()方法在提交事物,在向數(shù)據(jù)庫(kù)插入一條數(shù)據(jù)時(shí)必須要有這個(gè)方法,否則數(shù)據(jù)不會(huì)被真正的插入。
>>>conn.close()
Conn.close()關(guān)閉數(shù)據(jù)庫(kù)連接
六,插入數(shù)據(jù)
通過(guò)上面execute()方法中寫(xiě)入純的sql語(yǔ)句來(lái)插入數(shù)據(jù)并不方便。如:
>>>cur.execute("insert into student values('2','Tom','3 year 2 class','9')")
我要想插入新的數(shù)據(jù),必須要對(duì)這條語(yǔ)句中的值做修改。我們可以做如下修改:
#coding=utf-8
import MySQLdb
conn= MySQLdb.connect(
host='localhost',
port = 3306,
user='root',
passwd='123456',
db ='test',
)
cur = conn.cursor()
#插入一條數(shù)據(jù)
sqli="insert into student values(%s,%s,%s,%s)"
cur.execute(sqli,('3','Huhu','2 year 1 class','7'))
cur.close()
conn.commit()
conn.close()
假如要一次向數(shù)據(jù)表中插入多條值呢?
#coding=utf-8
import MySQLdb
conn= MySQLdb.connect(
host='localhost',
port = 3306,
user='root',
passwd='123456',
db ='test',
)
cur = conn.cursor()
#一次插入多條記錄
sqli="insert into student values(%s,%s,%s,%s)"
cur.executemany(sqli,[
('3','Tom','1 year 1 class','6'),
('3','Jack','2 year 1 class','7'),
('3','Yaheng','2 year 2 class','7'),
])
cur.close()
conn.commit()
conn.close()
executemany()方法可以一次插入多條值,執(zhí)行單挑sql語(yǔ)句,但是重復(fù)執(zhí)行參數(shù)列表里的參數(shù),返回值為受影響的行數(shù)。
七,查詢(xún)數(shù)據(jù)
也許你已經(jīng)嘗試了在python中通過(guò)
>>>cur.execute("select * from student")
來(lái)查詢(xún)數(shù)據(jù)表中的數(shù)據(jù),但它并沒(méi)有把表中的數(shù)據(jù)打印出來(lái),有些失望。
來(lái)看看這條語(yǔ)句獲得的是什么
>>>aa=cur.execute("select * from student")
>>>print aa
5
它獲得的只是我們的表中有多少條數(shù)據(jù)。那怎樣才能獲得表中的數(shù)據(jù)呢?進(jìn)入python shell
>>> import MySQLdb
>>> conn = MySQLdb.connect(host='localhost',port = 3306,user='root', passwd='123456',db ='test',)
>>> cur = conn.cursor()
>>> cur.execute("select * from student")
5L
>>> cur.fetchone()
(1L, 'Alen', '1 year 2 class', '6')
>>> cur.fetchone()
(3L, 'Huhu', '2 year 1 class', '7')
>>> cur.fetchone()
(3L, 'Tom', '1 year 1 class', '6')
...
>>>cur.scroll(0,'absolute')
fetchone()方法可以幫助我們獲得表中的數(shù)據(jù),可是每次執(zhí)行cur.fetchone() 獲得的數(shù)據(jù)都不一樣,換句話說(shuō)我沒(méi)執(zhí)行一次,游標(biāo)會(huì)從表中的第一條數(shù)據(jù)移動(dòng)到下一條數(shù)據(jù)的位置,所以,我再次執(zhí)行的時(shí)候得到的是第二條數(shù)據(jù)。
scroll(0,'absolute') 方法可以將游標(biāo)定位到表中的第一條數(shù)據(jù)。
還是沒(méi)解決我們想要的結(jié)果,如何獲得表中的多條數(shù)據(jù)并打印出來(lái)呢?
#coding=utf-8
import MySQLdb
conn= MySQLdb.connect(
host='localhost',
port = 3306,
user='root',
passwd='123456',
db ='test',
)
cur = conn.cursor()
#獲得表中有多少條數(shù)據(jù)
aa=cur.execute("select * from student")
print aa
#打印表中的多少數(shù)據(jù)
info = cur.fetchmany(aa)
for ii in info:
print ii
cur.close()
conn.commit()
conn.close()
通過(guò)之前的print aa 我們知道當(dāng)前的表中有5條數(shù)據(jù),fetchmany()方法可以獲得多條數(shù)據(jù),但需要指定數(shù)據(jù)的條數(shù),通過(guò)一個(gè)for循環(huán)就可以把多條數(shù)據(jù)打印出啦!執(zhí)行結(jié)果如下:
5 (1L, 'Alen', '1 year 2 class', '6') (3L, 'Huhu', '2 year 1 class', '7') (3L, 'Tom', '1 year 1 class', '6') (3L, 'Jack', '2 year 1 class', '7') (3L, 'Yaheng', '2 year 2 class', '7') [Finished in 0.1s]
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
- Python操作Mysql實(shí)例代碼教程在線版(查詢(xún)手冊(cè))
- MySQL-Python安裝問(wèn)題小記
- Python操作MySQL數(shù)據(jù)庫(kù)9個(gè)實(shí)用實(shí)例
- python連接mysql數(shù)據(jù)庫(kù)示例(做增刪改操作)
- python操作mysql中文顯示亂碼的解決方法
- 使用Python操作MySQL的一些基本方法
- python使用mysqldb連接數(shù)據(jù)庫(kù)操作方法示例詳解
- Python中操作mysql的pymysql模塊詳解
- 在Python安裝MySQL支持模塊的方法
- Python連接mysql數(shù)據(jù)庫(kù)的正確姿勢(shì)
相關(guān)文章
python批量修改文件夾及其子文件夾下的文件內(nèi)容
這篇文章主要為大家詳細(xì)介紹了python批量修改文件夾及其子文件夾下的文件內(nèi)容,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2019-03-03
python基于C/S模式實(shí)現(xiàn)聊天室功能
這篇文章主要為大家詳細(xì)介紹了python基于C/S模式實(shí)現(xiàn)聊天室功能,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2019-01-01
打印出python 當(dāng)前全局變量和入口參數(shù)的所有屬性
打印出python 當(dāng)前全局變量和入口參數(shù)的所有屬性的實(shí)現(xiàn)代碼。2009-07-07
Python中random.shuffle()函數(shù)用法代碼案例
random.shuffle方法,對(duì)元素進(jìn)行重新排序,打亂原有的順序,返回一個(gè)隨機(jī)序列,該方法的作用類(lèi)似洗牌,本文重點(diǎn)給大家介紹Python中random.shuffle()函數(shù)用法代碼案例,感興趣的朋友跟隨小編一起看看吧2022-11-11
Python3導(dǎo)入CSV文件的實(shí)例(跟Python2有些許的不同)
今天小編就為大家分享一篇Python3導(dǎo)入CSV文件的實(shí)例(跟Python2有些許的不同),具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2018-06-06
Python隨機(jī)生成身份證號(hào)碼及校驗(yàn)功能
這篇文章主要介紹了Python隨機(jī)生成身份證號(hào)碼及校驗(yàn)功能,文中給大家提到了校驗(yàn)碼計(jì)算方法,需要的朋友可以參考下2018-12-12
Pycharm中配置使用Anaconda的虛擬環(huán)境進(jìn)行項(xiàng)目開(kāi)發(fā)的圖文教程
今天在一臺(tái)電腦上跑環(huán)境的時(shí)候,發(fā)現(xiàn)已經(jīng)裝了Pytorch了,但是運(yùn)行沒(méi)有用,提示報(bào)錯(cuò):OSError:?[WinError?126]?找不到指定的模塊,但其實(shí)cmd進(jìn)入虛擬環(huán)境是可以調(diào)用torch的,故本文給大家介紹了Pycharm中配置使用Anaconda的虛擬環(huán)境進(jìn)行項(xiàng)目開(kāi)發(fā)的圖文教程2024-09-09
Python 給定的經(jīng)緯度標(biāo)注在地圖上的實(shí)現(xiàn)方法
今天小編就為大家分享一篇Python 給定的經(jīng)緯度標(biāo)注在地圖上的實(shí)現(xiàn)方法,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2019-07-07
解決Ubuntu18中的pycharm不能調(diào)用tensorflow-gpu的問(wèn)題
這篇文章主要介紹了解決Ubuntu18中的pycharm不能調(diào)用tensorflow-gpu的問(wèn)題,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2020-09-09

