python---basic knowledge review (8) database basic operations (sqlite and mysql)

One: sqlite operation

SQLite is an embedded database, and its database is a file. Since SQLite itself is written in C and is small in size, it is often integrated into various applications, even in iOS and Android apps.

Python has built-in SQLite3, so to use SQLite in Python, you don't need to install anything, just use it directly.

Steps:

1. Create a connection (remember to import the module)

import sqlite3
 conn = sqlite3.connect("test.db") #If the file does not exist, it will be created automatically. The path can be relative or absolute. This file is equivalent to a database

2. Get the cursor based on the connection

curs = conn.cursor()

3. Operate the data table according to the cursor

curs.execute( """ create table info( 
                    uid INTEGER PRIMARY KEY AUTOINCREMENT , #Pay attention to setting the primary key, which must be of type INTEGER
                    username varchar(20),
                    password varchar(32)
                )
            """ ) 

curs.execute( """
                 CREATE INDEX un on info (username) #Create index
 """ ) 
Related basics

4. Add, delete, modify and check data


curs.execute(""" INSERT INTO info(username,password) VALUES ("ld","123456"); """) delete curs.execute(""" DELETE FROM info WHERE uid > 3; """) change curs.execute(""" UPDATE info SET username = "dsad" WHERE uid = 2; """)
find
info_all = curs.execute("""
              SELECT * from info;
""")

for row in curs.fetchall():
    print(row[0],row[1],row[2])

5. If we add, delete, modify and modify the database, the original data (or data table) is gone, we need to submit our operation

conn.commit()

6. The operation is completed, disconnect the cursor and database connection

curs.close()
conn.close()

 

Two: mysql operation

 The mysql operation requires us to import the pymysql module (not built-in).

pip3 install pymysql

(1) The operation steps are almost the same as the above sqlite

import pymysql

conn = pymysql.connect(host= " localhost " ,user= " root " ,password= " root " ,database= " t1 " ) #Charset encoding can be set

cur = conn.cursor() #Set the cursor, the default is to return tuple information after executing the query
#cur = conn.cursor(cursor=pymysql.cursors.DictCursor) #Set the cursor to return dictionary type information
#Execute SQL statement
sql = "select * from users"
cur.execute(sql) #Execute the SQL statement and return the number of records after the query is successful

ret = cur.fetchall() #return tuple information
print (ret)
#((1, 'xiaoyu', 'xiaoudaf', '123'), (2, 'xiaoyu', 'xiaoudafc', '123'),)
cur.close() conn.close()

(2) SQL injection

For the information input by the user, we do not directly splicing, we need to filter, or use the module method to directly help us solve this problem

# It turns out that we are doing string concatenation to sql
# sql="select * from userinfo where name='%s' and password='%s'" %(user,pwd)
# print(sql)
# res=cursor.execute(sql)

#Rewrite as (execute helps us do string concatenation, we don't need and must not add quotes to % s)
sql = " select * from userinfo where name=%s and password=%s " #! ! ! Note that % s needs to be unquoted, because pymysql will automatically add it for us
res =cursor.execute(sql,[user,pwd]) #pymysql module automatically helps us solve the problem of sql injection, as long as we follow the rules of pymysql.

(3) Additions, deletions and modifications require commit

Add one 
sql at a time = ' insert into users(name,fullname,password) VALUES ("dsada","dasdasf","dsad") ' cur.execute(sql) sql = ' insert into users(name,fullname,password) VALUES (%s,%s,%s) ' cur.execute(sql,( " aaaaa " , " asd666 " , " 6666 ") ) #Get
the last insert The auto-incrementing ID of a piece of data
print(cur.lastrowid) #Only one can be added at a time. It can be seen directly. For adding more than one at a time, the number needs to be added.
Execute multiple items at once
sql = 'insert into users(name,fullname,password) VALUES (%s,%s,%s)'
cur.executemany(sql,[("aaadsaaa","asd6dasd66","6666"),("adsaaaaa","asd6awf66","6666"),("awaaaaa","asd666","6666")])

Note that after execute and executemany are executed, the number of bars affected by the execution will be returned

(4) Query

sql = " select * from users " 
rows = cur.execute(sql) #Returns the affected function rows, the results are placed in a collection, waiting for the query

ret = cur.fetchone() #Get a piece of data
print (ret) # ( 1 , ' xiaoyu ' , ' xiaoudaf ' , ' 123 ' )

ret = cur.fetchmany( 2 ) #Get the specified amount of data, from the current position
print (ret) # (( 2 , ' xiaoyu ' , ' xiaoudafc ' , ' 123 ' ), ( 3 , ' daf ' , ' fafwafs ' , ' times ' ))

ret = cur.fetchall() #Get all the data under the current location
print (ret)

#move cursor position
cur.scroll(0,mode="absolute")
ret = cur.fetchall() #Get all the data
print (ret)

cur.scroll( - 5 ,mode= " relative " ) #The cursor is at the end, now move 5 bars forward relative to the last
ret = cur.fetchall() #Get the last 5 pieces of data
print (ret)

 

Guess you like

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