美文网首页
Python操作SQLITE数据库

Python操作SQLITE数据库

作者: 火卫控 | 来源:发表于2022-08-11 18:15 被阅读0次

Python操作SQLITE数据库
filename.db
无需部署,可以用DBBROWSER查看

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

# 引入SQlite操作包

import  sqlite3

# 新建连接db数据库,创建表
conn=sqlite3.connect("D:\\Docus\\databases\\python_databases\\abbre2.db")

print("数据库创建成功!")
conn.execute("""
CREATE TABLE STUD_REGISTRATION(
STU_ID INTEGER PRIMARY KEY NOT NULL ,
STU_NAME TEXT NOT NULL, 
STU_CONTACT TEXT,
STU_EMAIL TEXT,
STU_ROLLNO TEXT NOT NULL,
STU_BRANCH TEXT NOT NULL)
""")
print ("STUD_REGISTRATION表创建成功!")


# 向表中写入数据
conn=sqlite3.connect("D:\\Docus\\databases\\python_databases\\abbre2.db")
conn.execute("INSERT INTO STUD_REGISTRATION (STU_ID,STU_NAME,STU_CONTACT,STU_EMAIL,STU_ROLLNO,STU_BRANCH) \
      VALUES (1,'Raju', '9179876567', 'raju@gmail.com','MCA204', 'CA')");
conn.execute("INSERT INTO STUD_REGISTRATION (STU_ID,STU_NAME,STU_CONTACT,STU_EMAIL,STU_ROLLNO,STU_BRANCH) \
      VALUES (2,'Nancy', '9179785695', 'nancy@gmail.com','MCA225', 'CA')");

conn.commit()
print ("记录插入成功!")
conn.close()


# 获取数据库,读取数据并按格式打印

conn = sqlite3.connect("D:\\Docus\\databases\\python_databases\\abbre2.db")

cursor = conn.execute("SELECT * from STUD_REGISTRATION")
print("NAME\tCONTACT\t\tEMAIL\t\t\tROLLLNO\tBRANCH")
for row in cursor:
   print ("{}\t{}\t{}\t{}\t{}".format(row[1],row[2],row[3],row[4],row[5]))
conn.close()


相关文章

网友评论

      本文标题:Python操作SQLITE数据库

      本文链接:https://www.haomeiwen.com/subject/aadtgrtx.html