Python语法 (1).md


http://www.runoob.com/python/python-exceptions.html

函数或者其它语句都可以另存为.py
调用时候需要先放入路径,然后import name.然后调用 moto.moto(cycle)


# coding: utf-8
#name:moto

# In[ ]:

import time
import random
def moto(cycle):
    tik = time.time()
    count=0
    cycle=2**10
    x_inp=[]
    y_inp=[]
    x_out=[]
    y_out=[]
    #循环
    for i in range(cycle):
        #生成一个随机点
        x,y=random.random(),random.random()
        #判断是否在圆内
        if x**2+y**2<1:
            count+=1
            x_inp.append(x)
            y_inp.append(y)
        else:
            x_out.append(x)
            y_out.append(y)
    tok= time.time()
    pi = 4*count/cycle
    print(pi)
    print(tok-tik)


将代码另存为.py

将.py文件放入工作目录

import 模块

import语句

包的管理

anaconda的直接使用conda命令即可。
管理员权限下打开cmd运行命令。
安装

  • conda install packagename
    更新
  • conda update-all

导入自己编写的内容

赌徒必输练习

赌徒必输理论

已知一赌徒,使用加倍加注法进行押注。假设该赌徒的胜率为50% 资本为N,尝试证明该赌徒最后必会输光。
加倍押注指的是,以一单位(假设此处为1元)作为第一场的押注,如果赢了,继续以一元押注,如果输了则以2元押注,2元押注如果输了则继续翻倍,直到赢。赢了后则再从一元开始押注。

import random
import matplotlib.pyplot as plt#画图的包,as后面是别名,方便调用
%matplotlib inline
def never_lose(dollar,cycle,d=0.5):
    # 设定一个资金曲线

    history = [dollar]
    # 初始化赌资倍数
    times = 0
    # 循环
    for i in range(cycle):
        # 确定压多少
        money=2**times
    #    if history[-1]>money:
    #        pool = money
    #    else:
    #        pool = history[-1]
        pool = money if history[-1]>money else history[-1]
        # 开盘,胜率050%,
        flag = random.random()
        # 计算赌资
        win = (1 if flag > d else -1)*pool
        history.append(history[-1]+win)
        # 重新调整下赌资倍数
        times = 0 if win>0 else (times+1)
        # 赌资为0,停止循环
        if history[-1]<=0:
            print("经过{}循环,输光了还剩下{}钱".format(i,history[-1]))
            break
    #循环结束,计算赌资
    print("经过{}循环,没输光,还剩下{}钱".format(len(history)-1,history[-1]))
    plt.plot(history)

第九章 IO操作

IO表示input/output,也就是输入和输出

查看文件编码

为了文件的打开关闭更方便,也可以使用with语句来自动帮我们调用close()方法。

import chardet
#参数rb为使用二进制打开
with open("bikes.csv","rb") as f:#相当于try。。。finally f.close(),关闭文件
    data=f.read()
    print(chardet.detect(data))
#确认编码打开文件
f = open("bikes.csv",encoding= 'ISO-8859-1')
f = open("bikes.csv",encoding= 'ISO-8859-1')
f.readlines()
f.close()

操作文件和目录

import os
for x,y,z in os.walk(r"D:\python_workspace"):
    print(x)#返回文件夹内文件夹名称
    print(y)#返回目录内文件名称
    print(z)#返回文件夹内文件名称

第十章 日期和时间

第十一章 *类和面向对象

python面向对象

1. 真实世界中的对象

函数可以把一些代码收集到能够反复使用的单元中,列表可以收集变量,对象则让这种收集的思想更向前迈进一步。对象可以把函数和数据收集在一起。

什么是对象?

对象是对现实事物的抽象,拿球举个例子,可以操作一个球,比如捡球、抛球、踢球或者充气。我们把这些操作称为动作。还可以通过指出球的颜色、大小和重量来描述一个球。这些就是球的属性。

真实世界的真实对象包括两个方面。

  • 可以对它们做什么(动作)。
  • 如果描述(属性或特征)。

2. python中的对象

在python中,一个对象的特征成为属性,动作称为方法。如果要建立一个球python版本或者模型,球就是一个对象,它有属性和方法。

  • 球的属性可能包括球的颜色、球的大小、球的重量
  • 球的方法包括kick、throw、inflate等操作

什么是属性

属性就是你所知道的关于球的所有方面。球的属性就是一些信息

什么是方法

方法就是可以对对象做的操作,它们是一些代码块,可以调用这些代码块来完成某个工作。其实,方法就是包含在对象中的函数。

函数能做到的,方法都可以做到,包括传递参数和返回值。

3. 创建对象

python中创建对象包括两步。

  • 第一步是定义对象看上去什么样,会做点什么,也就是它的属性和方法。但是创建这个描述并不会真正创建一个对象。这有点像一个房子的蓝图。蓝图可以告诉你房子看上去怎么样,但是蓝图本身并不是一个房子。你不可能住在一个蓝图里。只能用它来建造真正的房子。实际上,可以使用蓝图盖很多的房子。在python中,对象的描述或蓝图称为一个类(class)。
  • 第二步是使用类来建立一个真正的对象。这个对象称为这个类的一个实例(instance)

创建一个简单的Ball类

class Ball:
    def bounce(self):
        if self.direction == "down":
            self.direction = "up"

创建一个对象实例

类定义并不是一个对象,这只是蓝图,现在来盖真正的房子。

上面创建的类中,球还没有任何属性,所以给它提供一些属性,这是为对象定义属性的一种方法

class Ball:
    def bounce(self):
        if self.direction == "down":
            self.direction = "up"
myBall = Ball()
myBall.direction = "down"
myBall.color = "red"
myBall.size = "small"

print("I just created a ball.")
print("My ball is",myBall.size)
print("My ball is",myBall.color)
print("My ball's direction is",myBall.direction)

myBall.bounce()
print("Now the ball's direction is",myBall.direction)
I just created a ball.
My ball is small
My ball is red
My ball's direction is down
Now the ball's direction is up

4. 初始化对象

创建球对象时,并没有在size、color或direction中填入任何内容。必须在创建对象之后填充这些内容。不过有一种方法可以在创建对象时设置属性。这称为初始化对象。

初始化表示“开始时做好准备”。在软件中对某个东西初始化时,就是把它设置成一种我们希望的状态或条件,以备使用。

创建类定义时,可以定义一个特定的方法,名为__init__(),只要创建这个类的一个新实例,就会运行这个方法。可以向__init__()方法传递参数,这样创建实例时就会把属性设置为你希望的值。

class Ball:
    def __init__(self,color,size,direction):
        self.color = color
        self.size = size
        self.direction = direction
        
    def bounce(self):
        if self.direction == "down":
            self.direction = "up"
myBall = Ball("red","small","down")

print("I just created a ball.")
print("My ball is",myBall.size)
print("My ball is",myBall.color)
print("My ball's direction is",myBall.direction)

myBall.bounce()
print("Now the ball's direction is",myBall.direction)
I just created a ball.
My ball is small
My ball is red
My ball's direction is down
Now the ball's direction is up

5 . “魔法”方法:str()

myBall
<__main__.Ball at 0x16a0a0cdf60>

要改变这个显示,需要加入一个__str__()方法,让它返回你真正想打印的内容。这样一来,每次使用myBall时,它就会显示你想要的东西,这就是python中的一个“魔法”xxxx()类方法!

魔法方法是在你创建类时python自动包含的一些方法。我们会把它们叫做特殊方法。

我们已经知道,init()方法会在对象创建时完成初始化。每个对象都内置有一个__init__()方法。如果你在类定义中没有加入自己的__init__()方法,就会有这样一个内置方法接管,它的工作就是创建对象。

另一个特殊方法是__str__(),它会告诉python打印(print)一个对象时具体显示什么内容。

class Ball:
    def __init__(self,color,size,direction):
        self.color = color
        self.size = size
        self.direction = direction
        
    def __str__(self):
        msg = "Hi,I'm a " + self.size + " "+ self.color + "ball!"
        return msg
myBall = Ball("red","small","down")
print(myBall)
Hi,I'm a small redball!

6 .什么是self

你可能已经注意到,在类属性和方法定义中多处出现了"self",self是什么意思?我们说过,可以使用蓝图盖很多个房子,使用一个类也可以创建多个对象实例,方法必须知道是哪个实例调用了它,self参数会告诉方法哪个对象调用它。这称为实例引用。

调用方法时,warrensBall.bounce()的括号里没有参数,但是方法里却又一个self参数。既然我们并没有传入任何东西,这个self参数从哪里来的?这是python处理对象的另外一个"魔法"。调用一个类方法时,究竟是哪个实例调用了这个方法?这个信息(也就是实例引用)会自动传递给方法。

self这个名字在python中没有任何特殊的含义。只不过所有人都使用这个实例引用名。这也是让代码更易读的一个约定。也可以把这个实例变量命名为你想要的任务名字,不过强烈建议你遵循这个约定,因为使用self能减少混乱。

7. 一个示例类--Hotdog

定义类,先定义__init__()方法,它会为热狗设置默认属性:

class HotDog:
    def __init__(self):
        self.cooked_level = 0
        self.cooked_string = "Raw"
        self.condiments = []

先从一个没有加任何配料的生热狗开始,建立一个方法考热狗

def cook(self,time):
    self.cooked_level = self.cooked_level + time
    if self.cooked_level > 8:
        self.cooked_string = "Charcoal"
    elif self.cooked_level > 5:
        self.cooked_string = "Well done"
    elif self.cooked_level > 3:
        self.cooked_string = "Medium"
    else:
        self.cooked_string = "Raw"

创建一个实例,并且检查它的属性

class HotDog:
    def __init__(self):
        self.cooked_level = 0
        self.cooked_string = "Raw"
        self.condiments = []
    def cook(self,time):
        self.cooked_level = self.cooked_level + time
        if self.cooked_level > 8:
            self.cooked_string = "Charcoal"
        elif self.cooked_level > 5:
            self.cooked_string = "Well done"
        elif self.cooked_level > 3:
            self.cooked_string = "Medium"
        else:
            self.cooked_string = "Raw"
myDog = HotDog()
print(myDog.cooked_level)
print(myDog.cooked_string)
print(myDog.condiments)
0
Raw
[]

现在我们用cook方法

class HotDog:
    def __init__(self):
        self.cooked_level = 0
        self.cooked_string = "Raw"
        self.condiments = []
    def cook(self,time):
        self.cooked_level = self.cooked_level + time
        if self.cooked_level > 8:
            self.cooked_string = "Charcoal"
        elif self.cooked_level > 5:
            self.cooked_string = "Well done"
        elif self.cooked_level > 3:
            self.cooked_string = "Medium"
        else:
            self.cooked_string = "Raw"
myDog = HotDog()
print(myDog.cooked_level)
print(myDog.cooked_string)
print(myDog.condiments)
print("Now I'm going to cook the hot dog")
myDog.cook(4)
print(myDog.cooked_level)
print(myDog.cooked_string)
0
Raw
[]
Now I'm going to cook the hot dog
4
Medium

现在我们增加一些配料,另外还可以自己增加__str__()函数,让打印对象更为容易

class HotDog:
    def __init__(self):
        self.cooked_level = 0
        self.cooked_string = "Raw"
        self.condiments = []
    def __str__(self):
        msg = "hot dog"
        if len(self.condiments)>0:
            msg = msg + " with "
        for i in self.condiments:
            msg = msg+i+", "
        msg = msg.strip(", ")
        msg = self.cooked_string+ " "+msg+"."
        return msg
    def cook(self,time):
        self.cooked_level = self.cooked_level + time
        if self.cooked_level > 8:
            self.cooked_string = "Charcoal"
        elif self.cooked_level > 5:
            self.cooked_string = "Well done"
        elif self.cooked_level > 3:
            self.cooked_string = "Medium"
        else:
            self.cooked_string = "Raw"
    def addCondiment(self,condiment):
        self.condiments.append(condiment)
        
myDog = HotDog()
print(myDog)
print("Cooking hot dog for 4 minutes...")
myDog.cook(4)
print(myDog)
print("Cooking hot dog for 3 more minutes...")
myDog.cook(3)
print(myDog)
print("What happens if I cook it for 10 more minutes?")
myDog.cook(10)
print(myDog)
print("Now,I'm going to add some stuff on my hot dog")
myDog.addCondiment("ketchup")
myDog.addCondiment("mustard")
print(myDog)
Raw hot dog.
Cooking hot dog for 4 minutes...
Medium hot dog.
Cooking hot dog for 3 more minutes...
Well done hot dog.
What happens if I cook it for 10 more minutes?
Charcoal hot dog.
Now,I'm going to add some stuff on my hot dog
Charcoal hot dog with ketchup, mustard.

程序的第一部分创建了类。第二部分测试了烤这个虚拟热狗和添加配料的方法。

class HotDog:
    def __init__(self):
        self.cooked_level = 0
        self.cooked_string = "Raw"
        self.condiments = []
    def __str__(self):
        msg = "hot dog"
        if len(self.condiments)>0:
            msg = msg + " with "
        for i in self.condiments:
            msg = msg+i+", "
        msg = msg.strip(", ")
        msg = self.cooked_string+ " "+msg+"."
        return msg
    def cook(self,time):
        self.cooked_level = self.cooked_level + time
        if self.cooked_level > 8:
            self.cooked_string = "Charcoal"
        elif self.cooked_level > 5:
            self.cooked_string = "Well done"
        elif self.cooked_level > 3:
            self.cooked_string = "Medium"
        else:
            self.cooked_string = "Raw"
    def addCondiment(self,condiment):
        self.condiments.append(condiment)

8. 多态和继承

多态---同一个方法,不同的行为

多态是指对于不同的类,可以有同名的两个(或多个)方法。取决于这些方法分别应用到哪个类,它们可以有不同的行为。

假设你要建立一个程序做几何题,需要计算不同形状的面积,比如三角形和正方形

class Triangle:
    def __init__(self,width,height):
        self.width = width
        self.height = height
    
    def getArea(self):
        area = self.width * self.height/2.0
        return area
    
class Square:
    def __init__(self,size):
        self.size = size 
        
    def getArea(self):
        area = self.size * self.size
        return area
myTriangle = Triangle(4,5)
mySquare = Square(7)
myTriangle.getArea()
10.0
mySquare.getArea()
49

Triangle类和Square类都有一个名为getArea()的方法。所以,如果分别有这两个类的实例,这两个形状都使用了方法名getArea(),不过每个形状中这个方法做的工作不同。

继承--向父母学习

在真实的世界中,人们可以从他们的父母或者其他亲戚那里继承一些东西。你可以继承一些特征,比如说红头发,或者可以继承像钱和财产之类的东西

在面向对象编程中,类可以从其他类继承属性和方法。这样就有了类的整个"家族",这个"家族"中的每个类共享相同的属性和方法。这样一来,每次向"家族"增加新成员时就不必从头开始。

从其他类继承属性或方法的类称为派生类或子类。举个例子:假设我们要建立一个游戏,玩家一路上可以捡起不同的东西,比如食物、钱或衣服,可以建一个类,名为GameObject。GameObject类有name等属性和pickUp()等方法。所有游戏对象都有这些共同的方法和属性。

然后,可以为硬币建立一个子类。Coin类从GameObject派生。他要继承GameObject的属性和方法,所以Coin类会自动有一个name属性和pickUp()方法。Coin类还需要一个value属性和一个spend()方法。

class GameObject:
    def __init__(self,name):
        self.name = name
        
    def pickup(self,player):
        if player =="xiaoming":
            print("little coin")
    

class Coin(GameObject):
    def __init__(self,value):
        GameObject.__init__(self,"coin")
        self.value = value
        
    def spend(self,buyer,seller):
        pass
my_coin = Coin(45)
my_coin.name
'coin'
my_coin.pickup("xiaoming")
little coin
 

第十二章 连接数据库

在 Python 里面进行数据分析或者清洗, 导出导入数据时, 有时候我们直接读取数据文件, 而有的时候我们则需要去连接数据库.

本篇文章就针对一些常用的数据库 MySQL 和 SQLite3 的连接做一些演示.
之所以加入 SQLite3 是因为 Python 有内置该数据库, 非常方便于使用.

MySQL

在 Python 3 里面主要使用 MySQL 官方的 mysql-connector-python 和 pymysql 这两个库.
在 Python 2 里, 还有一些常见的库, 但是有些没有继续支持3(好像最近MySQLdb也有3的版本了), 本篇主要讲 Python 3 因此以上面两个库为例.

数据库的链接基本上都是大同小异, 但是很多细小的地方往往会导致一些不易查明的异常, 所以在这里做一个总结性的教程.
这里不涉及数据库的SQL语句相关的内容.

使用 mysql-connector-python 连接MySQL数据库.
import mysql.connector
创建数据库 "sampledb"
def create_db_sampledb():
    config_root = {
        "host": "localhost",
        "user": "root",
        "password": "1234"}  # 创建root用户的链接配置
    sql =  "Create Database If Not Exists sampledb CHARSET=utf8 COLLATE=utf8_bin"
    try:
        conn =  mysql.connector.connect(**config_root)
        cursor = conn.cursor()
        cursor.execute(sql)
        conn.commit()
    finally:
        conn.close()
        
create_db_sampledb()

配置 sampledb 连接信息 (全局使用, 后面的操作均在该数据库里进行)

mysql_config_sampledb ={
    "host":"127.0.0.1", 
    "database":"sampledb", 
    "user":"root", 
    "password":"1234"}
创建表
def create_table_sampletb():
    """如果该表不存在, 创建该表"""
    sql = (
        "Create Table If Not Exists sampletb( "
        "PassengerId int Primary key, "
        "Survived int(1), "
        "Pclass int(1), "
        "Name varchar(100), "
        "Sex varchar(10), "
        "Age int(3), "
        "SibSp int(1), "
        "Parch int(1), "
        "Ticket varchar(20), "
        "Fare float, "
        "Cabin varchar(100), "
        "Embarked varchar(10))")
    try:
        conn =  mysql.connector.connect(**mysql_config_sampledb)# 两个星号表示字典
        cursor = conn.cursor()
        cursor.execute(sql)
        conn.commit()
    finally:
        conn.close()
        
create_table_sampletb()
删除表
def drop_table_sampletb():
    """如果该表存在, 删除该表"""
    sql = "DROP TABLE IF EXISTS sampletb"
    try:
        conn =  mysql.connector.connect(**mysql_config_sampledb)
        cursor = conn.cursor()
        cursor.execute(sql)
        conn.commit()
    finally:
        conn.close()
        
drop_table_sampletb()
create_table_sampletb()  # 重新建立该表
插入数据
import pandas as pd
def insert_into_sampletb():
    df = pd.read_csv(r"C:\Users\CDAer\Desktop\施洪光\第六阶段python\python课件\python_basic\train.csv")
    df = df.where(~pd.isnull(df), other=None)#~表示反过来,pd.isnull(df)返回布尔值。前面有波浪线,所有有缺失值为~True=False
    
    sql = (
        "INSERT INTO sampletb "
        "(PassengerId,Survived,Pclass,Name,Sex,Age,SibSp,Parch,Ticket,Fare,Cabin,Embarked) "
        "VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s)")
    try:
        conn = mysql.connector.connect(**mysql_config_sampledb)
        cursor = conn.cursor()
        # cursor.executemany(sql, multiple_data)  # 插入多条记录, 其中multiple_data为list, 其中每一条记录为一个元组. 
        # cursor.execut(sql, data)  # 插入单条数据, 其中data记录为一个元组. 
        for row in df.iterrows():
            li = row[1].values
            cursor.execute(sql, tuple(li))  # 此处为插入单条数据

        conn.commit()
    finally:
        conn.close()
        
insert_into_sampletb()

更新数据同理

查询数据
select_sampletb = "SELECT * FROM sampletb LIMIT 100"  # 查询数据
select_sampletb_columns = "SHOW columns FROM sampletb"  # 查看表列名
def select_from_sampletb(config, sql):
    """查询语句, 输入数据库的链接信息(字典)以及查询语句.
    打印查询条数, 并返回查询的结果.
    """
    try:
        conn = mysql.connector.connect(**config)
        cursor = conn.cursor()
        cursor.execute(sql)
        result = cursor.fetchall()
    finally:
        conn.close()
    return result
result = select_from_sampletb(mysql_config_sampledb, select_sampletb)
type(result)
list
print(result[0:3])
[(1, 0, 3, bytearray(b'Braund, Mr. Owen Harris'), bytearray(b'male'), 22, 1, 0, bytearray(b'A/5 21171'), 7.25, None, bytearray(b'S')), (2, 1, 1, bytearray(b'Cumings, Mrs. John Bradley (Florence Briggs Thayer)'), bytearray(b'female'), 38, 1, 0, bytearray(b'PC 17599'), 71.2833, bytearray(b'C85'), bytearray(b'C')), (3, 1, 3, bytearray(b'Heikkinen, Miss. Laina'), bytearray(b'female'), 26, 0, 0, bytearray(b'STON/O2. 3101282'), 7.925, None, bytearray(b'S'))]
select_from_sampletb(mysql_config_sampledb, select_sampletb_columns)
[('PassengerId', 'int(11)', 'NO', 'PRI', None, ''),
 ('Survived', 'int(1)', 'YES', '', None, ''),
 ('Pclass', 'int(1)', 'YES', '', None, ''),
 ('Name', 'varchar(100)', 'YES', '', None, ''),
 ('Sex', 'varchar(10)', 'YES', '', None, ''),
 ('Age', 'int(3)', 'YES', '', None, ''),
 ('SibSp', 'int(1)', 'YES', '', None, ''),
 ('Parch', 'int(1)', 'YES', '', None, ''),
 ('Ticket', 'varchar(20)', 'YES', '', None, ''),
 ('Fare', 'float', 'YES', '', None, ''),
 ('Cabin', 'varchar(100)', 'YES', '', None, ''),
 ('Embarked', 'varchar(10)', 'YES', '', None, '')]
使用 pymysql 连接MySQL数据库.

与使用 mysql-connector-python 非常相似

import pymysql 
创建数据库 "sampledb2"
def creat_database_sampledb2():
    config_root = {
        "host": "localhost",
        "user": "root",
        "password": "1234"}
    sql = "Create Database If Not Exists sampledb2 CHARSET=utf8 COLLATE=utf8_bin"
    conn = pymysql.connect(**config_root)  # 打开数据库连接
    try:
        with conn.cursor() as cursor:  # 使用cursor()方法获取操作游标,并在语句结束自动关闭
            cursor.execute(sql)  # 执行SQL
            conn.commit()  # 提交
    finally:
        conn.close()

creat_database_sampledb2()

配置 sampledb2 连接信息 (全局使用, pymysql后面的操作均在该数据库里进行)

pymysql_config_sampledb2 ={
    "host":"127.0.0.1", 
    "database":"sampledb2", 
    "user":"root", 
    "password":"1234"}
创建表
def create_table_sampletb2():
    """如果该表不存在, 创建该表"""
    sql = (
        "Create Table If Not Exists sampletb2( "
        "PassengerId int Primary key, "
        "Survived int(1), "
        "Pclass int(1), "
        "Name varchar(100), "
        "Sex varchar(10), "
        "Age int(3), "
        "SibSp int(1), "
        "Parch int(1), "
        "Ticket varchar(20), "
        "Fare float, "
        "Cabin varchar(100), "
        "Embarked varchar(10))")
    conn = pymysql.connect(**pymysql_config_sampledb2)  # 打开数据库连接, 官方并没有把这个写在try语句并有解释.
    try:
        with conn.cursor() as cursor:
            cursor.execute(sql)
            conn.commit()
    finally:
        conn.close()

create_table_sampletb2()
删除表
def drop_table_sampletb2():
    """如果该表存在, 删除该表"""
    sql = "DROP TABLE IF EXISTS sampletb2"
    conn = pymysql.connect(**pymysql_config_sampledb2)
    try:
        with conn.cursor() as cursor:
            cursor.execute(sql)
            conn.commit()
    finally:
        conn.close()

drop_table_sampletb2()
create_table_sampletb2()  # 重新建立该表
插入数据
import pandas as pd
def insert_into_sampletb2():
    df = pd.read_csv("/WorkSpace/Data/titanic/train.csv")
    df = df.where(~pd.isnull(df), other=None)
    
    sql = (
        "INSERT INTO sampletb2 "
        "(PassengerId,Survived,Pclass,Name,Sex,Age,SibSp,Parch,Ticket,Fare,Cabin,Embarked) "
        "VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s)")
    conn = pymysql.connect(**pymysql_config_sampledb2)
    try:
        with conn.cursor() as cursor:
            # cursor.executemany(sql, multiple_data)
            # cursor.execut(sql, data)
            for row in df.iterrows():
                li = row[1].values
                cursor.execute(sql, tuple(li))  # 此处为插入单条数据
            conn.commit()
    finally:
        conn.close()

insert_into_sampletb2()

更新数据同理

查询数据
select_sampletb2 = "SELECT * FROM sampletb2 LIMIT 100"  # 查询数据
select_sampletb2_columns = "SHOW columns FROM sampletb2"  # 查看表列名
def select_from_sampletb2(config, sql):

    conn = pymysql.connect(**config)
    try:
        with conn.cursor() as cursor:
            cursor.execute(sql)
            result = cursor.fetchall()
    finally:
        conn.close()
    return result
result = select_from_sampletb2(pymysql_config_sampledb2, select_sampletb2)
type(result)
tuple
print(result[0:3])
((1, 0, 3, 'Braund, Mr. Owen Harris', 'male', 22, 1, 0, 'A/5 21171', 7.25, None, 'S'), (2, 1, 1, 'Cumings, Mrs. John Bradley (Florence Briggs Thayer)', 'female', 38, 1, 0, 'PC 17599', 71.2833, 'C85', 'C'), (3, 1, 3, 'Heikkinen, Miss. Laina', 'female', 26, 0, 0, 'STON/O2. 3101282', 7.925, None, 'S'))
select_from_sampletb2(pymysql_config_sampledb2, select_sampletb2_columns)
(('PassengerId', 'int(11)', 'NO', 'PRI', None, ''),
 ('Survived', 'int(1)', 'YES', '', None, ''),
 ('Pclass', 'int(1)', 'YES', '', None, ''),
 ('Name', 'varchar(100)', 'YES', '', None, ''),
 ('Sex', 'varchar(10)', 'YES', '', None, ''),
 ('Age', 'int(3)', 'YES', '', None, ''),
 ('SibSp', 'int(1)', 'YES', '', None, ''),
 ('Parch', 'int(1)', 'YES', '', None, ''),
 ('Ticket', 'varchar(20)', 'YES', '', None, ''),
 ('Fare', 'float', 'YES', '', None, ''),
 ('Cabin', 'varchar(100)', 'YES', '', None, ''),
 ('Embarked', 'varchar(10)', 'YES', '', None, ''))

SQLite3

import sqlite3

在使用SQLite3去连接一个数据库时, 如果该数据库存在, 那么就会连接上这个数据库.
如果这个数据库不存在, 那么会创建这个数据库, 并连接上.

设置一个路径, 作为数据库的路径

sqlite3_path = "sqlite_sample.db"
创建一个数据库, 并且创建一个表.
def create_sqlite_sampletb(db_path):
    sql = (
        "Create Table If Not Exists sampletb( "
        "PassengerId int Primary key, "
        "Survived int(1), "
        "Pclass int(1), "
        "Name varchar(100), "
        "Sex varchar(10), "
        "Age int(3), "
        "SibSp int(1), "
        "Parch int(1), "
        "Ticket varchar(20), "
        "Fare float, "
        "Cabin varchar(100), "
        "Embarked varchar(10))")
    
    with sqlite3.connect(db_path) as conn:
        cursor = conn.cursor()
        cursor.execute(sql)
        conn.commit()

create_sqlite_sampletb(sqlite3_path)

若想删除数据库, 直接删除.db文件就行了

删除表
def drop_sqlite_sampletb(db_path):
    sql = "DROP TABLE IF EXISTS sampletb"
    
    with sqlite3.connect(db_path) as conn:
        cursor = conn.cursor()
        cursor.execute(sql)
        conn.commit()

drop_sqlite_sampletb(sqlite3_path)
create_sqlite_sampletb(sqlite3_path)  # 新建表

查看当前数据库中的所有的表

def select_all_tables(db_path):
    sql = "SELECT name FROM sqlite_master WHERE type='table' ORDER BY name"  # 或者select * 查看表结构
    with sqlite3.connect(db_path) as conn:
        cursor = conn.cursor()
        cursor.execute(sql)
        conn.commit()
    return cursor.fetchall()

select_all_tables(sqlite3_path)
[('sampletb',)]
插入数据
def insert_into_sqlite_sampletb(db_path):
    df = pd.read_csv("/WorkSpace/Data/titanic/train.csv")
    df = df.where(~pd.isnull(df), other=None)
    
    sql = (
        "INSERT INTO sampletb "
        "(PassengerId,Survived,Pclass,Name,Sex,Age,SibSp,Parch,Ticket,Fare,Cabin,Embarked) "
        "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)")
    with sqlite3.connect(db_path) as conn:
        cursor = conn.cursor()
        # cursor.executemany(sql, multiple_data)
        # cursor.execut(sql, data)
        for row in df.iterrows():
            li = row[1].values
            cursor.execute(sql, tuple(li))
        conn.commit()

insert_into_sqlite_sampletb(sqlite3_path)
查询数据
def select_sqllite_sampletb(db_path):
    sql = "SELECT * FROM sampletb LIMIT 100"

    with sqlite3.connect(db_path) as conn:
        cursor = conn.cursor()
        cursor.execute(sql)
        conn.commit()
    return cursor.fetchall()
result = select_sqllite_sampletb(sqlite3_path)
type(result)
list
print(result[0:3])
[(1, 0, 3, 'Braund, Mr. Owen Harris', 'male', 22, 1, 0, 'A/5 21171', 7.25, None, 'S'), (2, 1, 1, 'Cumings, Mrs. John Bradley (Florence Briggs Thayer)', 'female', 38, 1, 0, 'PC 17599', 71.2833, 'C85', 'C'), (3, 1, 3, 'Heikkinen, Miss. Laina', 'female', 26, 0, 0, 'STON/O2. 3101282', 7.925, None, 'S')]

利用Pandas和数据库交互

在较多情景下, 可以直接去数据库读取我们想要的数据, 并转化为 Pandas 中的 DataFrame 数据格式.

import pandas as pd
import sqlalchemy
MySQL + mysql-connector-python
import mysql.connector
mysql_engine = sqlalchemy.create_engine('mysql+mysqlconnector://root:1234@localhost/sampledb', encoding='utf-8')
pd.read_sql('show tables', mysql_engine)
 Tables_in_sampledb
0 sampletb
MySQL + pymysql
import pymysql
pymysql_engine = sqlalchemy.create_engine('mysql+pymysql://root:1234@localhost/sampledb', encoding='utf-8')
pd.read_sql("SELECT * FROM sampletb LIMIT 10", pymysql_engine)
 PassengerIdSurvivedPclassNameSexAgeSibSpParchTicketFareCabinEmbarked
0 1 0 3 Braund, Mr. Owen Harris male 22.0 1 0 A/5 21171 7.2500 None S
1 2 1 1 Cumings, Mrs. John Bradley (Florence Briggs Th... female 38.0 1 0 PC 17599 71.2833 C85 C
2 3 1 3 Heikkinen, Miss. Laina female 26.0 0 0 STON/O2. 3101282 7.9250 None S
3 4 1 1 Futrelle, Mrs. Jacques Heath (Lily May Peel) female 35.0 1 0 113803 53.1000 C123 S
4 5 0 3 Allen, Mr. William Henry male 35.0 0 0 373450 8.0500 None S
5 6 0 3 Moran, Mr. James male NaN 0 0 330877 8.4583 None Q
6 7 0 1 McCarthy, Mr. Timothy J male 54.0 0 0 17463 51.8625 E46 S
7 8 0 3 Palsson, Master. Gosta Leonard male 2.0 3 1 349909 21.0750 None S
8 9 1 3 Johnson, Mrs. Oscar W (Elisabeth Vilhelmina Berg) female 27.0 0 2 347742 11.1333 None S
9 10 1 2 Nasser, Mrs. Nicholas (Adele Achem) female 14.0 1 0 237736 30.0708 None C
SQLite3
sqlite_engine = sqlalchemy.create_engine('sqlite:////WorkSpace/Data/sqlite_sample.db', encoding='utf-8')
pd.read_sql("SELECT * FROM sampletb LIMIT 10", sqlite_engine)
 PassengerIdSurvivedPclassNameSexAgeSibSpParchTicketFareCabinEmbarked
0 1 0 3 Braund, Mr. Owen Harris male 22.0 1 0 A/5 21171 7.2500 None S
1 2 1 1 Cumings, Mrs. John Bradley (Florence Briggs Th... female 38.0 1 0 PC 17599 71.2833 C85 C
2 3 1 3 Heikkinen, Miss. Laina female 26.0 0 0 STON/O2. 3101282 7.9250 None S
3 4 1 1 Futrelle, Mrs. Jacques Heath (Lily May Peel) female 35.0 1 0 113803 53.1000 C123 S
4 5 0 3 Allen, Mr. William Henry male 35.0 0 0 373450 8.0500 None S
5 6 0 3 Moran, Mr. James male NaN 0 0 330877 8.4583 None Q
6 7 0 1 McCarthy, Mr. Timothy J male 54.0 0 0 17463 51.8625 E46 S
7 8 0 3 Palsson, Master. Gosta Leonard male 2.0 3 1 349909 21.0750 None S
8 9 1 3 Johnson, Mrs. Oscar W (Elisabeth Vilhelmina Berg) female 27.0 0 2 347742 11.1333 None S
9 10 1 2 Nasser, Mrs. Nicholas (Adele Achem) female 14.0 1 0 237736 30.0708 None C