Python3 SQLite、MySQL数据库编程

参考廖雪峰的Python教程,实现Python3 SQLite、MySQL数据库编程

SQLite

#!/usr/bin/python3
# coding: utf-8

db_name = "test.db"
db_existed = False 

import os 
import sqlite3 

for root, dirs, files in os.walk("."):
    if db_name in files:
        db_existed = True 

conn = sqlite3.connect("test.db")
cursor = conn.cursor()

if not db_existed:
    cursor.execute('''
            create table user (
              id varchar(20) primary key,
              name varchar(20))
            ''')
    
    for i in range(1, 10):
        cursor.execute("insert into user values(\"%s\", \"python%s\")" %(i, i))
    
    conn.commit()

cursor.execute("select id, name from user")
values = cursor.fetchall()

for value in values:
    print(value[0], value[1])

cursor.execute("select id, name from user where id = ?", ("3"))
values = cursor.fetchall()

for value in values:
    print(value[0], value[1])

cursor.execute("select id, name from user where id = ? or name = ?", ("3", "python3"))
values = cursor.fetchall()

for value in values:
    print(value[0], value[1])

cursor.close()
conn.close()

MySQL

#!/usr/bin/python3 
# coding: utf-8

import mysql.connector 

conn = mysql.connector.connect(user="xxx", password="xxx", database="python")
cursor = conn.cursor()

cursor.execute("drop table if exists user;")
cursor.execute("create table user(id varchar(20) primary key, name varchar(20));")
conn.commit()

for i in range(1, 10):
    cursor.execute("insert into user values(%s, %s);", ["%s" %(i), "python%s" %(i)])

conn.commit()
cursor.close()

cursor = conn.cursor()
cursor.execute("select id, name from user;")
values = cursor.fetchall()
for value in values:
    print(value[0], value[1])

cursor.execute("select id, name from user where id = %s or name = %s;", [3, "python3"])
values = cursor.fetchall()
for value in values:
    print(value[0], value[1])

cursor.close()
conn.close()

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值