Python 創建數據表
阿新 • • 發佈:2017-11-22
__name__ table user div import usr 連接 final --
其實跟 Python 執行 MySQL 事務的操作差不多:
[root@localhost ~]# cat 1.py #!/usr/bin/env python import MySQLdb def connect_mysql(): db_config = { ‘host‘: ‘127.0.0.1‘, ‘port‘: 3306, ‘user‘: ‘root‘, ‘passwd‘: ‘pzk123‘, ‘db‘: ‘test‘ } c = MySQLdb.connect(**db_config)return c if __name__ == ‘__main__‘: c = connect_mysql() # 先連接數據庫 cus = c.cursor() sql = ‘‘‘ # 定義建表語句 create table t1( id int primary key not null, name varchar(10) not null, ageint not null ); ‘‘‘ try: cus.execute(sql) # 創建數據表 c.commit() except Exception as e: c.rollback() raise e finally: c.close()
結果如下:
[root@localhost ~]# 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 創建數據表