python3创建表及表数据;

winmeanyoung 2019-12-25

创建表,参考代码如下;

import pymysqltest=pymysql.connect(‘localhost‘,‘root‘,‘root‘,‘test1225‘)curs=test.cursor()curs.execute(‘drop table if exists xixi‘)sql="""create table `xixi`(`names` varchar(255) default null,`age` int(3) default null,`income` decimal(8,2) default 0)ENGINE=InnoDB DEFAULT charset=utf8;"""curs.execute(sql)test.close()

python3创建表及表数据;

 向表中添加数据;

方式一、

import pymysqltest=pymysql.connect(‘localhost‘,‘root‘,‘root‘,‘test1225‘)curs=test.cursor()sql="""insert into `xixi` values(‘xiaohua‘,34,888.3)"""curs.execute(sql)test.commit()test.close()方式二、#从外部传入参数
import pymysqltest=pymysql.connect(‘localhost‘,‘root‘,‘root‘,‘test1225‘)curs=test.cursor()names=‘张的美‘age=18curs.execute(‘insert into xixi(names,age) values("%s",%d)‘%(names,age))test.commit()test.close()方式三、错误回滚
import pymysqltest=pymysql.connect(‘localhost‘,‘root‘,‘root‘,‘test1225‘)curs=test.cursor()names=‘张的美‘age=18money=888try:    curs.execute(‘insert into xixi values("%s",%d,%f)‘ % (names, age, money))    test.commit()except:    test.rollback()    print(‘执行错误,并且已回滚‘)test.close()
 

相关推荐