Import pymysql # connect to the database, port must be int type, character encoding is UTF8, can not be utf8, password must be a string Conn = pymysql.connect (= Host 'database IP ' , = User 'user1 ' , password = ' 123456 ' , db = ' db_name ' , Port = 3306, charset = ' utf8 ' , True autocommit =) # establish a connection CUR = conn.cursor () # establish a cursor, the cursor can be used as warehouse manager cur.execute ( ' the Tables Show; ' ) # just help you execute sql statement Print (cur.fetchall ()) #Sql statement executed acquisition result SQL1 = " SELECT * from app_student limit. 5; " cur.execute (SQL1) Print (cur.fetchall ()) # fetch all data SQL2 = " SELECT * from app_student WHERE name = 'SMH' " CUR .execute (SQL2) Print (cur.fetchone ()) # take only one, if a plurality of returned results, taking only the first SQL3 = " SELECT * from app_student WHERE name = 'HHH' " cur.execute (SQL3) Print (cur.fetchmany (. 3)) # take several sql4 = " INSERT app_student (` name`, sex` `,` age`, addr` `,` grade`, phone` `,` gold`) " \ "values ( 'Test', 'Girl', '18 is', 'Beijing', 'JXZ', '13,121,211,111', '100'); " cur.execute (sql4) conn.commit () # submission, update, delete, insert these statements modify the database, need to commit to successfully execute # added autocommit = True in the connect automatically submit cur.close () # close the cursor conn.Close () # close the connection, use the connection over to off, or will account database
The sql execution returns the result into the dictionary format:
Import pymysql # connect to the database, port must be int type, character encoding is UTF8, can not be utf8, password must be a string Conn = pymysql.connect (= Host ' 118.24.3.40 ' , = User ' JXZ ' , password = ' 123456 ' , DB = ' JXZ ' , Port = 3306, charset = ' UTF8 ' , = True the autocommit) # establish a connection CUR = conn.cursor (pymysql.cursors.DictCursor) # pass a cursor type, may be shown as a dictionary sql5 = " SELECT * from app_student WHERE name = 'HHH' " cur.execute (sql5) Print(cur.fetchmany (. 3 )) cur.close () conn.Close () result: [{ ' ID ' : 328, ' name ' : ' HHH ' , ' Sex ' : ' Girl ' , ' Age ' : 18 is , ' addr ' : ' Jiyuan City, Henan Province North Avenue 32 ' , ' Grade ' : ' Scorpio ' , ' Phone ' : '18612539012', ' Gold ' : 100},
{ ' ID ' 345,: ' name ' : ' HHH ' , ' Sex ' : ' Girl ' , ' Age ' : 18 is, ' addr ' : ' Jiyuan City, Henan Province, 32 North Avenue, ' , ' Grade ' : ' Scorpio ' , ' Phone ' : ' 18,612,539,012 ', 'Gold ' : 100},
{ ' ID ' : 347, ' name ' : ' HHH ' , ' Sex ' : ' Girl ' , ' Age ' : 18 is, ' addr ' : ' Jiyuan City, North Avenue, 32 ' , ' Grade ' : ' Scorpio ' , ' Phone ' : ' 18,612,539,012 ' , 'gold': 100}]