python3與mysql:創建表、插入數據54


 
         
 1 import pymysql
 2 db = pymysql.connect(host='localhost',user='root',passwd='123456',db='jodb1',port=3307,charset='utf8')
 3 # #測試連接開發庫成功
 4 # db = pymysql.connect(host='172.31.20.2',user='root',passwd='sjroot',port=3306,charset='utf8')
 5 # print('heh')
 6 #數據中創建表
 7 cursor = db.cursor()
 8 cursor.execute('drop table if exists new_table2')
 9 print('Success!')
10 
11 
12 
13 sql = '''create table employee3 (
14 first_name char(20) not null,
15 last_name char(20),
16 age int ,
17 sex char(1),
18 income float)
19 '''
20 # 這樣修改語法有錯誤
21 # sql = '''create table employee3 if not exists employee3(
22 # first_name char(20) not null,
23 # last_name char(20),
24 # age int ,
25 # sex char(1),
26 # income float)
27 # '''
28 cursor.execute(sql)
29 db.close()
30 print('table create Successully!')
31 
32 
33 
34 
35 sql = '''insert into employee
36           (first_name,last_name,age,sex,income)
37           values('Jiang','LiGai',20,'F',2000)'''
38 try:
39     cursor.execute(sql)
40     db.commit()
41 except:
42     db.rollback()
43     db.close()
44 print('data insert successully')
45 
46 
47 #數據沒有插入成功,但是也沒有出錯
48 # sql2 = 'insert into employee(first_name,last_name,age,sex,income)values({0},{1},{2},{3},{4})'.format('Jiang','PeiRong',21,'F',3000)
49 # try:
50 #     cursor.execute(sql2)
51 #     db.commit()
52 # except:
53 #     db.rollback()
54 # print('data insert successully2')
 
         

 

 

 


免責聲明!

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



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