Python learning diary (thirty-seven) Mysql database chapter five

The use pymsql

Acquaintance pymysql module

Create a user information in a database table, which contains the user's ID, user name, password

create table userinfo(
    uid int not null auto_increment primary key,
    username varchar(32),
    pwd varchar(32)
)engine = innodb default charset=utf8;

Increase a user's information:

insert into userinfo(username,pwd) values('jxson','a123');

Users get the information from the database using simulated landing effect pymysql modules:

Import pymysql 
User = INPUT ( ' username: ' )                                                                # Enter the name of the user 
pwd = INPUT ( ' password: ' )                                                                 # Enter the user's password 
Conn = pymysql.connect (Host = ' localhost ' , = User ' the root ' , password = '' , database = ' DB1 ' )   # connect to the database 
cursor = conn.cursor ()                                                                  # The Cursor is a cursor to help us get the data 
sql_search = " the SELECT * from UserInfo the WHERE username = '% S' and pwd = '% S' " % (the User, pwd,)      # SQL statements 
cursor.execute (sql_search)                                                               # execution SQL statements 
get_one cursor.fetchone = ()                                                              # take a set of data 
cursor.close ()                                                                           # close the cursor 
conn.Close ()                                                                             # close the connection 
ifget_one:                                                                              # determine whether there is to get data 
    Print ( " successful landing! " )
     Print (get_one)                                      
 the else :
     Print ( " login failed! " )

Results of the:

username: jxson 
password: A123 
landing success! 
( 1, ' jxson ' , ' A123 ' )

Improved methods of preventing SQL injection

1.

sql_search = "select * from userinfo where username=%s and pwd=%s"                     
cursor.execute(sql_search,user,pwd)  

2. The list representation

sql_search = "select * from userinfo where username=%s and pwd=%s"                      
cursor.execute(sql_search,[user,pwd])

3. Dictionary representation

sql_search = "select * from userinfo where username=%(u)s and pwd=%(p)s"                      
cursor.execute(sql_search,{'u' : user,'p' : pwd})

 

Guess you like

Origin www.cnblogs.com/Fantac/p/11672330.html