一、建立表mysql
1 # 建立表student: 2 # 主鍵 3 # 主鍵,一種特殊的惟一索引,不容許有空值,若是主鍵使用單個列,則它的值必須惟一,若是是多列,則其組合必須惟一 4 student =''' 5 create table student( 6 stdid int primary key not null, 7 stdname varchar(100) not null, 8 gender enum('F','M'), 9 age int 10 ): 11 ''' 12 tmp=''' 13 set @a=0 14 create table tmp as select (@a :=@a+1)as id from information_schema.tables limit 10: 15 16 ''' 17 18 if __name__=="__main__": 19 cnx = connect_mysql() 20 print(cnx) 21 print(dir(cnx)) 22 cus=cnx.cursor() 23 try: 24 cus.execute(student) 25 cus.execute(tmp) 26 cus.close() 27 cnx.commit() 28 except Exception as e: 29 cnx.rollback() 30 raise e 31 finally: 32 cnx.close()
二、增長數據sql
1 #增長數據 2 # insert into 表 (列名,列名...) values (值,值,值...) 3 # insert into 表 (列名,列名...) select (列名,列名...) from 表 4 if __name__ == '__main__': 5 cnx = connect_mysql() 6 students = '''set @i := 10000; 7 insert into Student select @i:=@i+1, substr(concat(sha1(rand()), sha1(rand())), 1, 3 + floor(rand() * 75)), case floor(rand()*10) mod 2 when 1 then 'M' else 'F' end, 25-floor(rand() * 5) from tmp a, tmp b, tmp c, tmp d; 8 ''' 9 try: 10 cus_students = cnx.cursor() 11 cus_students.execute(students) 12 cus_students.close() 13 cnx.commit() 14 except Exception as e: 15 cnx.rollback() 16 raise e 17 finally: 18 cnx.close()
三、查詢fetch
1 #查詢數據 2 #select * from 表 3 # 條件查詢 4 # select * form 表 where 條件 5 # 通配符查詢 6 # select * from 表 where name like 'a%'以a開頭的若個字符 7 # 限制查詢 8 # select * from 表 limit 5;仟伍行 9 # select * from 表 order by 列 asc - 根據某一列從小到大排序(從大到小 desc -) 10 # 分組 11 # select num,id from 表 group by num,id 12 if __name__ == '__main__': 13 cnx = connect_mysql() 14 15 sql = '''select * from Student where StdName in (select StdName from Student group by StdName having count(1)>1 ) order by StdName;''' 16 #把全部名字重複的學生列出來 17 try: 18 cus = cnx.cursor() 19 cus.execute(sql) 20 result = cus.fetchall() 21 # 取出內容 22 #寫入到select。txt中 23 with codecs.open('select.txt', 'w+') as f: 24 for line in result: 25 f.write(str(line)) 26 27 f.write('\n') 28 cus.close() 29 cnx.commit() 30 except Exception as e: 31 cnx.rollback() 32 print('error') 33 raise e 34 finally: 35 cnx.close()