python3創建表及表數據;


創建表,參考代碼如下;

import pymysql
test=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()

 

 

 

 

 

 

 向表中添加數據;

方式一、

import pymysql
test=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 pymysql
test=pymysql.connect('localhost','root','root','test1225')
curs=test.cursor()
names='張的美'
age=18
curs.execute('insert into xixi(names,age) values("%s",%d)'%(names,age))
test.commit()
test.close()
方式三、錯誤回滾
import pymysql
test=pymysql.connect('localhost','root','root','test1225')
curs=test.cursor()
names='張的美'
age=18
money=888
try:
curs.execute('insert into xixi values("%s",%d,%f)' % (names, age, money))
test.commit()
except:
test.rollback()
print('執行錯誤,並且已回滾')
test.close()




免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM