Python learning (21) encryption module and database operation

1. MD5 encryption

You cannot directly encrypt the string, you must first convert the string to bytes type

import hashlib
m=hashlib.md5()
password = ' liujia test ' 
print (password.encode())   #Convert the string to bytes type 
m.update(password.encode()) # Can't encrypt the string directly, first convert the string to bytes type 
print (m.hexdigest())

Define function, do encryption

def my_md5(str):
    new_str =str.encode() #Convert the string to bytes type 
    # new_str=b'%s'%str #Convert the string to bytes type 
    m=hashlib.md5() #Instantiate   the MD5 object 
    m.update(new_str )   #encryption return m.hexdigest
     () #get   the result and return print (my_md5( ' jsjs ' ))

2. Other encryption methods

import hashlib
m =hashlib.sha224() #Various   encryption methods, the usage is the same, but the encrypted ciphertext is different 
m.update( ' adasdjks ' .encode())
 print (m.hexdigest())

3. Operating the database

Database operation steps: 
1) Connect to the database account, password, IP, port number, database

2) Create a cursor
3) Execute sql
4) Get the result
5) Close the cursor
6) Close the connection

Query database data:

import pymysql
coon=pymysql.connect(
    host='xxx.xx.x.x',user='jxz',password='123456',
    port =3306,db= ' jxz ' ,charset= ' utf8 ' 
# port must be int type, charset must write utf8 
)
cur =coon.cursor() #Create a cursor 
cur.execute( ' select * from stu; ' )
res =cur.fetchall() #Get all returned results 
print (res)
cur.close()   #Close the cursor 
coon.close() #Close the connection

Insert data:

import pymysql
coon=pymysql.connect(
    host='118.24.3.40',user='jxz',password='123456',
    port =3306,db= ' jxz ' ,charset= ' utf8 ' 
# port must be int type, charset must write utf8 
)
cur =coon.cursor() #Create a cursor 
cur.execute( ' insert into stu(id,name,sex) values(12,"liujia","test") ' )
coon.commit()
res =cur.fetchall() #Get all returned results 
print (res)
cur.close()   #Close the cursor 
coon.close() #Close the connection

4. Function definition database operation

def my_db(host,user,paaaword,db,sql,port3306,charset='utf8'):
    import pymysql
    coon=pymysql.connect(uesr=user,
                         host=host,
                         paaaword = paaaword,
                         db=db,
                         charset=charset,
    )
    cur=coon.cursor()
    cur.execute(sql)
    if sql.strip()[:6].upper()=='SELECT':
        res=cur.fetchall()
    else:
        coon.commit()
        res='ok'
    cur.close()
    coon.close()
    return res

 

 

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325172434&siteId=291194637