Python 連線mysql資料庫進行操作

at_1發表於2021-09-09


1.MySQLdb 模組是用於Python連結Mysql資料庫的介面,預設是沒有安裝的

[root@python ~]# yum  install  MySQL-python   -y


2.建立python指令碼

[root@python ~]# 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.執行指令碼,進庫檢視是否成功

[root@python ~]# 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)


來自 “ ITPUB部落格 ” ,連結:http://blog.itpub.net/1817/viewspace-2803610/,如需轉載,請註明出處,否則將追究法律責任。

相關文章