python from entry to proficiency 3 - advanced

1. Python MySQL

Install  mysql-connector:

python -m pip install mysql-connector

 

  • close(): Close the database connection. Using the database connection after closing will cause an exception.
  • commit(): Commit the database transaction.
  • rollback(): Rollback database transaction.
  • cursor(): Get Cursor cursor object. 
import mysql.connector
from mysql.connector import connect

my_db = connect(
     # 数据库主机地址
    host='localhost',
     # 数据库用户名
    user='root',
     # 数据库密码
    passwd='yourpassword',
    # 固定插件
    auth_plugin='mysql_native_password'
)
print(my_db)
#<mysql.connector.connection.MySQLConnection object at 0x0000014E918348E0>

 

1. Create a data table 

import mysql.connector
from mysql.connector import connect

my_db = connect(
     # 数据库主机地址
    host='localhost',
     # 数据库用户名
    user='root',
     # 数据库密码
    passwd='yourpassword',
    # 固定插件
    auth_plugin='mysql_native_password'
)
# 获取游标
mycursor = my_db.cursor()
# 创建数据库
mycursor.execute('CREATE DATABASE run_db')
# 查询数据库
mycursor.execute('SHOW DATABASES')
for i in  mycursor:

    print(i)

# 使用数据库
mycursor.execute(" USE run_db")
# 创建数据表
mycursor.execute('CREATE TABLE sites (name VARCHAR(255),url VARCHAR(255))')
# 查询数据表
mycursor.execute('SHOW TABLES')
for n in mycursor:
    print(n)

 2. Insert data

import mysql.connector
from mysql.connector import connect
my_db = connect(
      # 数据库主机地址
    host='localhost',
     # 数据库用户名
    user='root',
     # 数据库密码
    passwd='yourpassword',
    # 固定插件
    auth_plugin='mysql_native_password'
)
mycursor = my_db.cursor()
mycursor.execute('USE demo')
mycursor.execute('CREATE TABLE sites (name VARCHAR(255),url VARCHAR(255))')

# 插入数据
sql = 'INSERT INTO sites (name,url) VALUE (%s,%s)'
val = ('南栀北夏网站','jinghan.site')
mycursor.execute(sql,val)
# 在执行插入、更新或删除等修改数据库的操作后,必须调用 commit() 方法才能确保更改被保存到数据库中。
my_db.commit()
# mycursor.rowcount 返回最后一次执行 SQL 语句后受影响的行数
print(mycursor.rowcount,'记录插入成功')

 

 

 Batch insert

import mysql.connector
from mysql.connector import connect
my_db = connect(
      # 数据库主机地址
    host='localhost',
     # 数据库用户名
    user='root',
     # 数据库密码
    passwd='yourpassword',
    # 固定插件
    auth_plugin='mysql_native_password'
)
mycursor = my_db.cursor()
mycursor.execute('USE demo')

# 插入数据
sql = 'INSERT INTO sites (name,url) VALUE (%s,%s)'
val = [
    ('南栀北夏网站','jinghan.site'),
    ('百度','baidu.com'),
    ('github','https://www.github.com')
    ]
# executemany() 方法,并传递了 SQL 插入语句和要插入的多个值的列表
mycursor.executemany(sql,val)
# 在执行插入、更新或删除等修改数据库的操作后,必须调用 commit() 方法才能确保更改被保存到数据库中。
my_db.commit()
# mycursor.rowcount 返回最后一次执行 SQL 语句后受影响的行数
print(mycursor.rowcount,'记录插入成功')

 3. Query data


import mysql.connector
from mysql.connector import connect
my_db = connect(
      # 数据库主机地址
    host='localhost',
     # 数据库用户名
    user='root',
     # 数据库密码
    passwd='yourpassword',
    # 固定插件
    auth_plugin='mysql_native_password'
)
mycursor = my_db.cursor()
# 选择数据库
mycursor.execute('USE demo')
# 查询数据库
mycursor.execute('SELECT name,url FROM sites')
# mycursor.fetchall() 方法是执行查询操作后获取所有结果的方法
myresult = mycursor.fetchall()
for i in myresult:
    print(i)

 myresult = mycursor.fetchone(): To read a piece of data, you can use  the fetchone()  method

4. Delete records


import mysql.connector
from mysql.connector import connect
my_db = connect(
      # 数据库主机地址
    host='localhost',
     # 数据库用户名
    user='root',
     # 数据库密码
    passwd='yourpassword',
    # 固定插件
    auth_plugin='mysql_native_password'
)
mycursor = my_db.cursor()
# 选择数据库
mycursor.execute('USE demo')
# 删除数据
sql = "DELETE FROM sites WHERE name = '百度'"
#;另外一种方法:
#sql = "DELETE FROM sites WHERE name = %s"
#na = ("stackoverflow", )
#mycursor.execute(sql, na)
mycursor.execute(sql)
my_db.commit()
print(mycursor._rowcount,'条记录删除')


 5. Update table data


import mysql.connector
from mysql.connector import connect
my_db = connect(
      # 数据库主机地址
    host='localhost',
     # 数据库用户名
    user='root',
     # 数据库密码
    passwd='yourpassword',
    # 固定插件
    auth_plugin='mysql_native_password'
)
mycursor = my_db.cursor()
# 选择数据库
mycursor.execute('USE demo')
# 更新表数据
sql = "UPDATE sites SET name = 'zh' WHERE name = '南栀北夏网站'"
mycursor.execute(sql)
my_db.commit()
print(mycursor.rowcount,'条记录修改')


2. PyMySQL driver 

Install the latest version of PyMySQL

 pip3 install PyMySQL

1.Create database table

import pymysql
# 打开数据库连接
db = pymysql.connect(
    host='localhost',
    user='root',
    password='yourpassword',
    # 数据库名称
    database='demo'
)
# 创建一个游标对象
cusor = db.cursor()
# 创建数据库表
sql = """
    CREATE TABLE EMPLOTEE(
    name CHAR(20) NOT NULL,
    age INT,
    sex CHAR(1),
    INCOME FLOAT
    )
"""
cusor.execute(sql)
db.close()

 2. Insert data

import pymysql
# 打开数据库连接
db = pymysql.connect(
    host='localhost',
    user='root',
    password='yourpassword',
    # 数据库名称
    database='demo'
)
# 创建一个游标对象
cusor = db.cursor()
# sql插入数据
sql = "INSERT INTO EMPLOTEE(name,age,sex,INCOME) VALUES ('tom',18,'男',2000)"
try:
    # 执行sql语句
    cusor.execute(sql)
    # 提交到数据库执行
    db.commit()
except Exception as e:
    print('发生错误',e)

    # 发生错误时回滚
    db.rollback()

# 关闭数据库
db.close()





 3. Query data

  • fetchone():  This method gets the next query result set. The result set is an object
  • fetchall():  Receive all returned result lines.
  • rowcount:  This is a read-only property and returns the number of rows affected after executing the execute() method.

 

import pymysql

# 打开数据库连接
db = pymysql.connect(
    host='localhost',
    user='root',
    password='yourpassword',
    database='demo'
)

# 创建一个游标对象
cursor = db.cursor()

# SQL 查询数据
sql = "SELECT * FROM EMPLOTEE WHERE INCOME > %s" % (1000)

try:
    db.commit()
    cursor.execute(sql)
    result = cursor.fetchall()
    for row in result:
        name = row[0]
        age = row[1]
        sex = row[2]
        income = row[3]
        print("name=%s, age=%s, sex=%s, income=%s" % (name, age, sex, income))
except Exception as e:
    print('代码异常:', str(e))

# 关闭游标和数据库连接
cursor.close()
db.close()

4.Update data 

import pymysql

# 打开数据库连接
db = pymysql.connect(
    host='localhost',
    user='root',
    password='yourpassword',
    database='demo'
)

# 创建一个游标对象
cursor = db.cursor()

# sql更新数据
sql = "UPDATE EMPLOTEE SET AGE = AGE + 1 WHERE SEX = '%c'" % ('男')
try:
    # 执行sql
    cursor.execute(sql)
    db.commit()
except Exception as e:
    print('代码异常',e)
    db.rollback()

db.close()

 5. Delete data

import pymysql

# 打开数据库连接
db = pymysql.connect(
    host='localhost',
    user='root',
    password='yourpassword',
    database='demo'
)

# 创建一个游标对象
cursor = db.cursor()

# sql删除数据
sql = "DELETE FROM EMPLOTEE WHERE AGE < 20"
try:
    cursor.execute(sql)
    db.commit()
except Exception as e:
    print(e)
    db.rollback()

db.close()
 

3. Python multithreading

Multithreading is similar to executing multiple different programs at the same time. Multithreading has the following advantages:

  • Threads can be used to process long-running tasks in the background.
  • The user interface can be more attractive. For example, when the user clicks a button to trigger the processing of certain events, a progress bar can pop up to show the progress of the processing.
  • The program may run faster.
  • Threads are more useful in the implementation of waiting tasks such as user input, file reading and writing, and network sending and receiving data. In this case we can release some precious resources such as memory usage and so on.

There are two ways to use threads in Python: functions or classes to wrap thread objects.

Functional: Call the start_new_thread() function in the _thread module to generate a new thread. The syntax is as follows:

_thread.start_new_thread ( function, args[, kwargs] )
  • function - the thread function.
  • args - the parameters passed to the thread function, which must be of type tuple.
  • kwargs - optional parameters

 Thread module——threading

  • threading.currentThread(): Returns the current thread variable.
  • threading.enumerate(): Returns a list containing running threads. Running refers to after the thread starts and before it ends, excluding threads before starting and after termination.
  • threading.activeCount(): Returns the number of running threads, which has the same result as len(threading.enumerate()).
  • run():  method used to represent thread activity.
  • start(): Start thread activity.

  • join([time]):  Wait until the thread terminates. This blocks the calling thread until the thread's join() method is called abort - exit normally or throw an unhandled exception - or an optional timeout occurs.
  • isAlive():  Returns whether the thread is active.
  • getName():  Returns the thread name.
  • setName():  Set the thread name.

 

import threading
import time 
exitFlag = 0
class myThread(threading.Thread):
    def __init__(self,threadID,name,delay):
        threading.Thread.__init__(self)
        self.threadID = threadID
        self.name = name
        self.delay = delay

    def run(self):
        print("开始线程:" + self.name)
        print_time(self.name,self.delay,5)
        print('退出线程:' + self.name)

def print_time(threadName,delay,counter):
    while counter:
        if exitFlag:
            threadName.exit()
        time.sleep(delay)
        print ("%s: %s" % (threadName, time.ctime(time.time())))
        counter -= 1

# 创建新线程
thread1 = myThread(1,'Thread-1',1)
thread2 = myThread(2,'Thread-2',2)

# 开启新线程
thread1.start()
thread2.start()
thread1.join()
thread2.join()
print('退出主线程')

 

 

 

Guess you like

Origin blog.csdn.net/m0_74421072/article/details/135323207