標籤:Python串連mysql資料庫進行操作
1.MySQLdb 模組是用於Python連結Mysql資料庫的介面,預設是沒有安裝的
[[email protected] ~]# yum install MySQL-python -y
2.建立python指令碼
[[email protected] ~]# cat mysql.py
#!/usr/bin/env python
#-*- coding: UTF-8 -*-
import MySQLdb as mysql #匯入MySQLdb模組
db=mysql.connect(user='root',passwd='centos',db='test',host='localhost') #串連資料庫
cursor=db.cursor() #建立遊標對象
sql='create table test(id int,name varchar(8));' #建立表
cursor.execute(sql) #執行sql語句
db.close() #關閉串連
3.執行指令碼,進庫查看是否成功
[[email protected] ~]# mysql -uroot -pcentos
mysql> use test;
Database changed
mysql> show tables;
+----------------+
| Tables_in_test |
+----------------+
| test |
+----------------+
1 row in set (0.00 sec)
mysql> desc test;
+-------+------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+-------+------------+------+-----+---------+-------+
| id | int(11) | YES | | NULL | |
| name | varchar(8) | YES | | NULL | |
+-------+------------+------+-----+---------+-------+
2 rows in set (0.00 sec)
Python 串連mysql資料庫進行操作