標籤:turn cursor python type __name__ 定義 creat nbsp arc
其實跟 Python 執行 MySQL 事務的操作差不多:
[[email protected] ~]# cat 1.py#!/usr/bin/env pythonimport MySQLdbdef connect_mysql(): db_config = { ‘host‘: ‘127.0.0.1‘, ‘port‘: 3306, ‘user‘: ‘root‘, ‘passwd‘: ‘pzk123‘, ‘db‘: ‘test‘ } c = MySQLdb.connect(**db_config) return cif __name__ == ‘__main__‘: c = connect_mysql() # 先串連資料庫 cus = c.cursor() sql = ‘‘‘ # 定義建表語句 create table t1( id int primary key not null, name varchar(10) not null, age int not null ); ‘‘‘ try: cus.execute(sql) # 建立資料表 c.commit() except Exception as e: c.rollback() raise e finally: c.close()
結果如下:
[[email protected] ~]# mysql -uroot -ppzk123 -e "use test; desc t1;"+-------+-------------+------+-----+---------+-------+| Field | Type | Null | Key | Default | Extra |+-------+-------------+------+-----+---------+-------+| id | int(11) | NO | PRI | NULL | || name | varchar(10) | NO | | NULL | || age | int(11) | NO | | NULL | |+-------+-------------+------+-----+---------+-------+
Python 建立資料表