標籤:python mysql
1、ubuntu環境下安裝python-MySQLdbsudo apt-get install build-essential python-dev libmysqlclient-devsudo apt-get install python-MySQLdb
2、或者PIP安裝
pip install mysql-python
3、安裝好之後匯入模組
import MySQLdb
4、登入資料庫後查看資料庫
mysql> show databases;
+--------------------+
| Database |
+--------------------+
| information_schema |
| mysql |
| performance_schema |
| sys |
+--------------------+
4 rows in set
5、建立資料庫
mysql> create database soms character set utf8;
Query OK, 1 row affected
6、建立表,表名discovery
create table discovery(id int(2) not null primary key auto_increment,ip varchar(40),port int(10),status text)default charset=utf8;
7、查看錶結構
mysql> desc discovery;
+--------+-------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+--------+-------------+------+-----+---------+----------------+
| id | int(2) | NO | PRI | NULL | auto_increment |
| ip | varchar(40) | YES | | NULL | |
| port | int(10) | YES | | NULL | |
| status | text | YES | | NULL | |
+--------+-------------+------+-----+---------+----------------+
4 rows in set
8、查詢表裡的資料
mysql> select * from discovery;
Empty set
目前沒有資料,是個空表
9、插入一條資料,並查詢
mysql> insert into discovery(ip,port,status) values("192.168.89.3",22,"True");
Query OK, 1 row affected
mysql> select * from discovery;
+----+--------------+------+--------+
| id | ip | port | status |
+----+--------------+------+--------+
| 1 | 192.168.89.3 | 22 | True |
+----+--------------+------+--------+
1 row in set
10、資料庫建立好之後,就可以用python通過已經安裝的mysqldb來串連這個名字叫做soms的庫了。
import MySQLdbDBHOST = "192.168.89.101"DBUSER = "root"DBPASSWD ="1qaz#EDC"DB = "soms"PORT = 3306CHARSET = "utf8"conn = MySQLdb.connect(host=DBHOST, user=DBUSER, passwd=DBPASSWD, db=DB, port=PORT, charset=CHARSET)
Python建立了與資料的串連,其實是建立了一個MySQLdb.connect()的執行個體對象,或者泛泛地稱之為連線物件,python就是通過連線物件和資料庫對話。這個對象常用的方法有:
commit():如果資料庫表進行了修改,提交儲存當前的資料。當然,如果此使用者沒有許可權就作罷了,什麼也不會發生。
rollback():如果有許可權,就取消當前的操作,否則報錯。
cursor([cursorclass]):返回串連的遊標對象。通過遊標執行SQL查詢並檢查結果。遊標比串連支援更多的方法,而且可能在程式中更好用。
close():關閉串連。此後,連線物件和遊標都不再可用了。
本文出自 “營運交流Q群:223843163” 部落格,請務必保留此出處http://freshair.blog.51cto.com/8272891/1903008
python操作mysql(一)MySQLdb模組安裝和資料庫基本操作