Analysis on the Important Matters of python Connection to Database

  • 2021-09-11 20:36:00
  • OfStack

1. update delete insert This statement requires commit or directly adds autocommit=True when connecting to the database


import pymysql

conn = pymysql.connect(
  host="",
  user="jxz",
  password="",
  db="jxz",
  port=3306,
  charset="utf8",
  autocommit=True

) # Connect to database
2. When there are many database contents,


for line in cursor:# Use it when there is a lot of table data 
  print(line)
# There are other indirect ways 
# result = cursor.fetchmany(5) # Get n Article 
#cursor.execute("select * from students limit 5;")

3. To get the typical data of the word, add: cursor = conn. cursor (pymysql. cursors. DictCursor) # when writing the cursor to create the cursor


cursor = conn.cursor(pymysql.cursors.DictCursor) # Create a cursor 

4. Overall code:


import pymysql
conn=pymysql.connect(host='',
        user='jxz',
        password='',
        db='jxz',
        port=3306,
        autocommit=True,
        charset='utf8')# Linked database 
cursor=conn.cursor()# Cursor 
# View all current tables 
#cursor.execute('create table lmmlmm(num int,str varchar (20));')
cursor.execute('insert into lmmlmm (num,str)values("1","limiaomiao");')
conn.commit()
result=cursor.fetchall()
cursor.close()
conn.close()
print(result)

5. The parameters of connection database can be written in the form of collection, and converted into key, value format by * *, which is convenient to call


import pymysql

mysql_info = pymysql.connect(
  host="",
  user="jxz",
  password="",
  db="jxz",
  port=3306,
  charset="utf8",
  autocommit=True
)# Connect to a database 
##** It can only be followed by a dictionary and can be converted to key , value
def execute_sql(sql,more=False,db_info=None):
 # select *from user where id=1 ; 
  if db_info:
    conn=pymysql.connect(**db_info)
  else:
    conn=pymysql.connect(**mysql_info)

Related articles: