Python connects to the database and operates on the database

Python connects to the database and operates on the database

The development environment involved in this article: Use Navicat under Ubuntu16.04 + MySQL5.7.21 and Windows to visually operate MySQL under Ubuntu. For the relevant installation steps of MySQL, see the previously published articles. The connection between Python and the database MySQL needs to use MySQLdb The download address click me , MySQLdb supports Python2. , and does not support Python3. .

Construction of basic development environment and software installation

MySQLdb installation

The installation of MySQLdb can pipbe installed using:

pip install MySQL-python==1.2.5

Connection between Navicat and MySQL (Ubuntu) under Windows

Before connecting, you need to make relevant settings for MySQL, because MySQL is 127.0.0.1bound to the local machine by default, and other hosts cannot access and modify data with the database. The relevant settings are as
follows /etc/mysql/mysql.conf.d: mysqld.cnfRevise.

lee@lee-PC:/etc/mysql/mysql.conf.d$ tree
.
├── mysqld.cnf
└── mysqld_safe_syslog.cnf

mysqld.cnfPart of the code is as follows, bind-address = 127.0.0.1comment out and you can access MySQL through other computers.

...
#
# Instead of skip-networking the default is now to listen only on
# localhost which is more compatible and is not less secure.
#  bind-address     = 127.0.0.1
#
...

Set the access authority of the data database, enter the database, and set it through the following commands, usernameyou can access and operate the database on any IP.

mysql> GRANT ALL PRIVILEGES ON *.* TO 'username'@'%' IDENTIFIED BY 'mypassword' WITH GRANT OPTION; 

You can connect directly through Navicat.
write picture description here

Python operates on MySQL

Python connects to MySQL -connection

  • Create a connection object and establish a network connection between the Python client and the database
  • The basic method created is MySQLdb.connect (related parameters). The main parameters are (host, user, passwd, port, db, charset). Among these parameters, only port is a number type, and other parameters are strings. Types of.

Execute on the database, get the structure of the execution - cursor

  • Cursor object: used to execute queries and get results
  • The cursor object contains the following methods:
parameter name illustrate
execute(command) Execute a database query and command
fetchone() Get the next row in the result set
fetchmany() Get the next few rows in the result set
fetchall() Get all the information in the result set
rowcount The most recent execute returns data or the number of rows affected
close() close cursor object

As an example

import MySQLdb
conn = MySQLdb.Connect(
    host = "127.0.0.1",
    port = 3306,
    user = "lee",
    passwd = "123",
    db = "lee",
    charset = "utf8",
)

cursor = conn.cursor()

sql_command = 'select * from user'

cursor.execute(sql_command)

rs = cursor.fetchall()


for ele in rs:
    print 'userid : %d , username : %s'  %ele

cursor.close()
conn.close()

commit() and rollback() operations

write picture description here

When we use cursor.execute(SQL) to execute an Insert/Update/Delete statement, we need to use conn.commit() to commit the transaction, otherwise, the statement will not take effect.

In fact, our commonly used commit() contains a concept of transaction processing. If you execute multiple statements before commit(), all of them will take effect only after commit().

Then if two insert statements are executed as mentioned at the beginning of the article, we can put the conn.commit() statement after the execution of the two insert statements and put it in the try statement block. If an exception occurs, we can use:

conn.rollback()

This statement causes the transaction to be rolled back to the point after the previous conn.commit() execution.

The following is a simple example, a rough application of commit() and rollback().

import MySQLdb
print MySQLdb

conn = MySQLdb.Connect(
    host = "127.0.0.1",
    port = 3306,
    user = "lee",
    passwd = "123",
    db = "lee",
    charset = "utf8"
)

cursor = conn.cursor()
sql_commond = 'select * from user '
cursor.execute(sql_commond)

for ele in cursor.fetchall():
    print "userid : %d, username : %s" %ele

print "*" * 8
# exe insert update delete
sql_insert = "insert into user(username) values('Lily')"
sql_update = "update user set username='Sweet' where userid=1"
sql_delete = "delete from user where userid=3"
# sql_delete = "delete from user where username='Lily'"
sql_insert = "insert into user(userame) values('Lily')"

try:
    cursor.execute(sql_insert)
    print cursor.rowcount
    cursor.execute(sql_update)
    print cursor.rowcount
    cursor.execute(sql_delete)
    print cursor.rowcount

    conn.commit()

except Exception as e:
    print e
    conn.rollback()

cursor.close()
conn.close()

The following is a strength, a comprehensive application of the above method - bank withdrawal.

# coding:utf8
import sys
import MySQLdb


class TransferMoney(object):
    def __init__(self, conn):
        self.conn = conn
    def transfer(self, source_accid, target_accid, money):
        try:
            self.check_acct_available(source_accid)
            self.check_acct_available(target_accid)
            self.has_enough_money(source_accid, money)
            self.reduce_money(source_accid, money)
            self.add_money(target_accid, money)
            self.conn.commit()
        except Exception as e:
            self.conn.rollback()
            raise e

    def check_acct_available(self, accid):
        try:
            cursor = self.conn.cursor()
            sql_command = 'select * from bankaccount where accid=%s' %accid
            print "check_acct_available" + sql_command
            cursor.execute(sql_command)
            rs = cursor.fetchall()
            if len(rs) != 1:
                raise Exception("账号%s 不错在" %accid) 
        finally:
             cursor.close()

    def has_enough_money(self, accid, money):
        try:
            cursor = self.conn.cursor()
            sql_command = 'select * from bankaccount where accid=%s and money > %s' %(accid, money)
            print "has_enough_money" + sql_command
            cursor.execute(sql_command)
            rs = cursor.fetchall()
            if len(rs) != 1:
                raise Exception("账号%s 的金额不足" %accid)

        finally:
             cursor.close()

    def reduce_money(self, accid, money):
        try:
            cursor = self.conn.cursor()
            sql_command = 'update bankaccount set money=money-%s where accid=%s' %(money, accid)
            print "reduce_money" + sql_command
            cursor.execute(sql_command)
            rs = cursor.fetchall()
            if cursor.rowcount != 1:
                raise Exception("账号%s 扣款失败" %accid)
        finally:
             cursor.close()

    def add_money(self, accid, money):
        try:
            cursor = self.conn.cursor()
            sql_command = 'update bankaccount set money=money+%s where accid=%s' %(money, accid)
            print "add_money" + sql_command
            cursor.execute(sql_command)
            rs = cursor.fetchall()
            if cursor.rowcount != 1:
                raise Exception("账号%s 入款失败" %accid)
        finally:
             cursor.close()




if __name__ == "__main__":
    source_accid = sys.argv[1]
    target_accid = sys.argv[2]
    money = sys.argv[3]

    conn = MySQLdb.connect(
        host = '127.0.0.1',
        user = 'lee',
        passwd = '123',
        port = 3306,
        db = 'lee'
    )
    tr_money = TransferMoney(conn)
    try:
        tr_money.transfer(source_accid, target_accid, money)
    except Exception as e:
        print "出现问题 :" + str(e)
    finally:
        conn.close()

Problems encountered in writing the above program, and solutions.

提示:
`TypeError:%d format:a number is required, not str.

The solution is to modify the format of the variable passed into sql. It is not necessary to write the corresponding variable in sql %d, just write it %s.

above.

Guess you like

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