其实跟 Python 执行 MySQL 事务的操作差不多:
[[email protected] ~]# 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, 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 | | +-------+-------------+------+-----+---------+-------+
时间: 2024-11-08 23:39:38