Python operates Mysql database

(1) What the python DB API contains:
               
(2) The process of accessing the database using the python DB API:
 
                  
(3) The main methods of the python DB API:
  • connect connection class:   
    • conn = pymsql.connect(host="localhost", port=3306, user="root", passwd="root", db="goods", charset="utf8"):创建一个mysql连接。
    • cursor = conn.cursor(): Create a cursor for communication between python and mysql, that is, to execute sql statements.
    • conn.rollback(): Rollback, so that after the SQL statement indicated by the cursor fails to execute, the database remains in the same state before execution.
    • conn.commit(): Confirm, so that after the SQL statement is executed, the database will change accordingly.
    • conn.close(): Close the connection.
  • cursor cursor class:   
    • cursor.execute(sql): The actual parameter is the string of the sql statement, which is used to execute the sql statement in MySQL.
    • cursor.fetchone(): Returns the next line of the query result, in the form of a tuple, ie: ((1 line), (2 line), (3 line)).
    • cursor.fetchsize(size): Returns the next size row of the query result, in the form of a tuple.
    • cursor.fetchall(): Returns the remaining rows of the query result, in the form of a tuple.
    • cursor.rowcount: The number of rows affecting the database in the most recent execution.
    • cursor.close(): closes the cursor.
(4) python3.6 operation database --- simple addition, deletion, modification and query:
import pymysql
 if  __name__ == ' __main__ ' :
 #Create MYSQL connection 
conn = pymysql.Connect(host = ' 127.0.0.1 ' ,port = 3306,user = ' root ' ,passwd = ' root ' ,db = ' databasetest ' , charset = ' utf8 ' )
 #Create a cursor: used for communication between Python and Mysql, ie: used to execute SQL statements. 
cursor = conn.cursor()
 try :
     #Add database 
    sql = "INSERT INTO userdata VALUES (1,'lbg'),(2,'zgj'),(3,'ldt')"
    cursor.execute(sql)
    #Delete database 
    sql2 = " DELETE FROM userdata WHERE id=3 "
    cursor.execute(sql2)
    #Update database 
    sql3 = " UPDATE userdata SET username='wjz' WHERE id=2 "
    cursor.execute(sql3)
    #Query database 
    sql4 = " SELECT * FROM userdata " 
    num = cursor.execute(sql4)
     print ( " the number of the userdata: %d " % num)
     # fetchall returns a tuple containing the results of all queries. 
    for row in cursor.fetchall(): 
         print ( " ID: " +str(row[0])+ " name: " +row[1 ])
 except Exception as reason:
     # SQL transaction rollback: transfer the transaction to the database All completed operations are undone and rolled back to the state at the beginning of the transaction 
    conn.rollback()
     print( ' Transaction failed ' , reason)
 else :
     # SQL transaction confirmation: database operations will take effect only after the transaction is confirmed 
    conn.commit()
     print ( ' transaction successful ' , cursor.rowcount)
 finally :
     #Close the connection and cursor 
    cursor.close()
    conn.close()
(5) python3.6 operation database --- bank transfer:
import pymysql
import sys

class TransferMoney:
    def __init__(self,conn):
        self.conn = conn
    def transfer(self,id_out,id_in,money):
        try:
            self.HasIdAccount (id_out)
            self.HasIdAccount(id_in)
            self.OutIdHasEnoughMoney(id_out,money)
            self.SubMoney(id_out,money)
            self.AddMoney(id_in,money)
            conn.commit()
        except Exception as e:
            self.conn.rollback()
            raise e
    def HasIdAccount(self,userid):
        cursor = self.conn.cursor()
        try:
            sql = "select * from goods_change where id = %s" % userid
            cursor.execute(sql)
            res = cursor.fetchall()
            if len(res) != 1:
                raise Exception("id %s is not exist" % userid)
                print("Has id " + str(userid))
        finally:
            cursor.close()
    def OutIdHasEnoughMoney(self,userid,change_money):
        cursor = self.conn.cursor()
        try:
            sql = "select money from goods_change where id = %s" % userid
            cursor.execute(sql)
            if int(cursor.fetchone()[0]) < int(change_money):
                raise Exception("id %s has not enough money" % userid)
                print("id " + str(userid) + " has enough money")
        finally:
            cursor.close()
    def SubMoney(self,userid,change_money):
        cursor = self.conn.cursor()
        try:
            sql = "update goods_change set money=money-%s where id=%s" % (change_money,userid)
            cursor.execute(sql)
            if cursor.rowcount != 1:
                raise Exception("id %s is not exist" % userid)
                print("id " + str(userid) + " sub " + str(change_money) + " RMB")
        finally:
            cursor.close()
    def AddMoney(self,userid,change_money):
        cursor = self.conn.cursor()
        try:
            sql = "update goods_change set money=money+%s where id=%s" % (change_money,userid)
            cursor.execute(sql)
            if cursor.rowcount != 1:
                raise Exception("id %s is not exist" % userid)
                print("id " + str(userid) + " add " + str(change_money) + " RMB")
        finally:
            cursor.close()

if __name__ == '__main__':
    conn = pymysql.Connect(host='127.0.0.1',port=3306,user='root',passwd='root',db='goods',charset='utf8')
    id_out = sys.argv[1]
    id_in = sys.argv[2]
    money = sys.argv[3]
    trans = TransferMoney(conn)
    try:
        trans.transfer(id_out,id_in,money)
    except Exception as reason:
         print ( ' Transaction failed: ' , reason)
     finally :
        conn.close()

 

Guess you like

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