admin
2025-06-10 568c763084b926a6f2d632b7ac65b9ec8280752f
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
import datetime
import logging
 
import pymysql
import sqlite3
 
config = {
    "host": "gz-cdb-r13d0yi9.sql.tencentcdb.com",
    "port": 62929,
    "database": "everyday_words",
    "charset": "utf8",
    "user": "root",
    "passwd": "Yeshi2016@"
}
 
 
class Mysqldb:
    # 初始化方法
    def __init__(self):
        # 初始化方法中调用连接数据库的方法
        self.conn = self.get_conn()
        # 调用获取游标的方法
        self.cursor = self.get_cursor()
 
    def close(self):
        self.conn.close()
 
    # 连接数据库的方法
    def get_conn(self):
        # **config代表不定长参数
        conn = pymysql.connect(**config)
        return conn
 
    # 获取游标
    def get_cursor(self):
        cursor = self.conn.cursor()
        return cursor
 
    # 查询sql语句返回的所有数据
    def select_all(self, sql):
        self.cursor.execute(sql)
        return self.cursor.fetchall()
 
    # 查询sql语句返回的一条数据
    def select_one(self, sql):
        self.cursor.execute(sql)
        return self.cursor.fetchone()
 
    # 查询sql语句返回的几条数据
    def select_many(self, sql, num):
        self.cursor.execute(sql)
        return self.cursor.fetchmany(num)
 
    # 增删改除了SQL语句不一样其他都是一样的,都需要提交
    def execute(self, sql, args=None):
        try:
            # 执行语句
            self.cursor.execute(sql, args)
            # 提交
            self.conn.commit()
        except Exception as e:
            print("提交出错\n:", e)
            logging.exception(e)
            # 如果出错要回滚
            self.conn.rollback()
 
    def execute_many(self, sql, args=None):
        try:
            # 执行语句
            self.cursor.executemany(sql, args)
            # 提交
            self.conn.commit()
        except Exception as e:
            logging.exception(e)
            print("提交出错\n:", e)
            # 如果出错要回滚
            self.conn.rollback()
 
    # 当对象被销毁时,游标要关闭,连接也要关闭
    # 创建时是先创建连接后创建游标,关闭时是先关闭游标后关闭连接
    def __del__(self):
        self.cursor.close()
        self.conn.close()
 
 
def save_to_sqlite(datas):
    sqlite_conn = sqlite3.connect('D:\\项目\\单词\\words.db')
    sqlite_cursor = sqlite_conn.cursor()
    for data in datas:
        sql = "insert into table_english_words values(?,?,?,?,?,?,?)"
        print(sql)
        sqlite_cursor.execute(sql, (data[0],
            data[1], data[2], data[3], data[4].strftime("%Y-%m-%d %H:%M"), data[5].strftime("%Y-%m-%d %H:%M"), data[6]))
    sqlite_conn.commit()
    sqlite_conn.close()
 
 
if __name__ == "__main__":
    for i in range(0, 50):
        results = Mysqldb().select_all(f"select * from table_english_words limit {i*1000}, 1000")
        save_to_sqlite(results)