Python使用sqlite3庫創建Mysql文件

Python使用sqlite3庫創建Mysql文件

使用方法都寫在程序裏面的註釋中,請盡情享用,如果您覺得不錯可以點個贊哦🙂
代碼如下:

# -*- coding:utf-8 -*-
import sqlite3

__author__ = 'Evan'


class SqliteDB(object):
    """
    在本地創建一個虛擬的Mysql文件
    """
    def __init__(self, db_path=r'C:\Users\evaliu\Desktop', db_name='sql_lite3'):
        self.db_path = db_path + '\\' + db_name
        self.cxn = sqlite3.connect(self.db_path)
        self.cur = self.cxn.cursor()

    def create_table(self):
        """
        創建一個數據表
        :return:
        """
        try:
            self.cur.execute('''
            CREATE TABLE users(
                uid INTEGER,
                prid INTEGER)
            ''')
        except Exception as e:
            print('Create Table Error, ERROR-MSG: [ {} ]'.format(e))
            print('Recreate the users now!')
            self.cur.execute('DROP TABLE users')
            self.create_table()

    def read_table(self):
        """
        讀取數據表
        :return:
        """
        print('Mysql dumps:')
        self.cur.execute('SELECT * FROM users')
        for each_line in self.cur.fetchall():
            print(each_line)


if __name__ == '__main__':
    mysql = SqliteDB()
    try:
        mysql.create_table()
        mysql.cur.execute('INSERT INTO users VALUES(100, 200)')
        mysql.read_table()
    finally:
        mysql.cur.close()
        mysql.cxn.commit()
        mysql.cxn.close()
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章