Python base (16) - operate the database module pymysql

A, pymysql module mounting

pip3 install pymysql

Second, connect to the database

2.1, create test data

mysql> create database AA;
mysql> use AA
mysql> create table test(id int primary key auto_increment,name varchar(25),passwd varchar(25));
mysql> insert into test(name,passwd) values('AA',123),('BB',456),('CC',789);
mysql> select * from test;
+----+------+--------+
| id | name | passwd |
+----+------+--------+
|  1 | AA   | 123    |
|  2 | BB   | 456    |
|  3 | CC   | 789    |
+----+------+--------+
3 rows in set (0.00 sec)

2.2, the database connection

! # / usr / bin / env Python 
# - * - Coding: UTF-8 - * - 
Import pymysql 
. the User = the INPUT ( "Username:") strip () 
. pwd = the INPUT ( "Password:") strip () 

# connection 
conn = pymysql.connect (Host = "10.0.0.12", Port = 3306, the User = "root", passwd = "MySQL", db = "AA") 

# cursor 
cursor = conn.cursor () # finished result set returned to the default display tuple 
# cursor = conn.cursor (cursor = pymysql.cursors.DictCursor ) # returns a dictionary 

# execute sql statement 
sql = 'select * from AA.test where name = "% s" and passwd = "% s" '% (user, pwd) # % s requires quotes Note 
Print (sql) 
RES = the cursor.execute (sql) # sql statement execution, the number of successful query returns sql recording 
Print (RES) 

# Close cursor and connection 
cursor.close () 
conn.Close () 

IF RES: 
    Print ( "Login successful ") 
the else: 
    Print (" login failed ")

Guess you like

Origin www.cnblogs.com/hujinzhong/p/11565889.html