python中sqlite用法_Python3 sqlite的简单用法

# -*- coding: utf-8 -*-

# @Time : 2018/9/13 10:25

# @Author :

# @Email :

# @File : sqlite_test.py

import sqlite3

import os

work_path_name = 'sqlite_test'

home_path = os.path.expanduser('~')

db_file_name = 'test.db'

db_file_path = os.path.join(home_path, work_path_name, db_file_name)

def get_conn(file_path):

'''

创建数据库文件

:param file_path:

:return:

'''

if os.path.isfile(file_path):

print('文件存在')

elif os.path.isdir(file_path):

print('包含%s文件价,删除' % file_path)

os.rmdir(file_path)

else:

print('未找到文件')

db_file_dir = os.path.dirname(file_path)

if os.path.isfile(db_file_dir):

print('有一个跟目录名一样的文件')

os.remove(db_file_dir)

os.makedirs(db_file_dir)

elif not os.path.exists(db_file_dir):

print('目录不存在创建,创建')

os.makedirs(db_file_dir)

return sqlite3.connect(db_file_path)

def get_cursor(conn):

'''

获取数据库操作游标对象

:param conn:

:return:

'''

if conn is not None:

print('获取游标对象')

return conn.cursor()

else:

print('conn is None')

def create_table(conn):

pass

def execute_sql(conn, sql):

'''

执行sql语句

:param conn:

:param sql:

:return:

'''

if sql is not None and sql != '':

cu = get_cursor(conn)

try:

cu.execute(sql)

except sqlite3.OperationalError as e:

print(e)

return

conn.commit()

close_all(conn, cu)

def close_all(conn, cu):

'''

关闭数据

:param conn:

:param cu:

:return:

'''

if cu != None:

cu.close()

if conn != None:

conn.close()

if __name__ == '__main__':

conn = get_conn(db_file_path)

execute_sql(conn, '''CREATE TABLE COMPANY(

ID INT PRIMARY KEY NOT NULL,

NAME TEXT NOT NULL,

AGE INT NOT NULL,

ADDRESS CHAR(50),

SALARY REAL

);''')

pass

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值