【Python】学习笔记总结9(数据库与Python交互)

引用自 https://www.runoob.com/python3/python3-mysql.html

九、数据库与Python交互

1.连接MYSQL数据库

1.1.创建表

import pymysql
# 打开数据库连接
db = pymysql.connect("数据库IP地址","用户名","密码","数据库" )
 
# 使用 cursor() 方法创建一个游标对象 cursor
cursor = db.cursor()
 
# 使用 execute() 方法执行 SQL,如果表存在则删除
cursor.execute("DROP TABLE IF EXISTS EMPLOYEE")
 
# 使用预处理语句创建表
sql = """CREATE TABLE EMPLOYEE (
         FIRST_NAME  CHAR(20) NOT NULL,
         LAST_NAME  CHAR(20),
         AGE INT,  
         SEX CHAR(1),
         INCOME FLOAT )"""
 
cursor.execute(sql)
 
# 关闭数据库连接
db.close()

1.2.插入数据

import pymysql
 
# 打开数据库连接
db = pymysql.connect("数据库IP地址","用户名","密码","数据库" )
 
# 使用cursor()方法获取操作游标 
cursor = db.cursor()
 
# SQL 插入语句
sql = """INSERT INTO EMPLOYEE(FIRST_NAME,
         LAST_NAME, AGE, SEX, INCOME)
         VALUES ('Mac', 'Mohan', 20, 'M', 2000)"""
# SQL 插入语句2
sql2 = "INSERT INTO EMPLOYEE(FIRST_NAME, \
       LAST_NAME, AGE, SEX, INCOME) \
       VALUES ('%s', '%s',  %s,  '%s',  %s)" % \
       ('Mac', 'Mohan', 20, 'M', 2000)
try:
   # 执行sql语句
   cursor.execute(sql)
   # 提交到数据库执行
   db.commit()
except:
   # 如果发生错误则回滚
   db.rollback()
 
# 关闭数据库连接
db.close()

1.3.查询数据

import pymysql
 
# 打开数据库连接
db = pymysql.connect("数据库IP地址","用户名","密码","数据库" )
 
# 使用cursor()方法获取操作游标 
cursor = db.cursor()
 
# SQL 查询语句
sql = "SELECT * FROM EMPLOYEE \
       WHERE INCOME > %s" % (1000)
try:
   # 执行SQL语句
   cursor.execute(sql)
   # 获取所有记录列表
   results = cursor.fetchall()
   for row in results:
      fname = row[0]
      lname = row[1]
      age = row[2]
      sex = row[3]
      income = row[4]
       # 打印结果
      print ("fname=%s,lname=%s,age=%s,sex=%s,income=%s" % \
             (fname, lname, age, sex, income ))
except:
   print ("Error: unable to fetch data")
 
# 关闭数据库连接
db.close()

1.4.更新数据

import pymysql
 
# 打开数据库连接
db = pymysql.connect("数据库IP地址","用户名","密码","数据库" )
 
# 使用cursor()方法获取操作游标 
cursor = db.cursor()
 
# SQL 更新语句
sql = "UPDATE EMPLOYEE SET AGE = AGE + 1 WHERE SEX = '%c'" % ('M')
try:
   # 执行SQL语句
   cursor.execute(sql)
   # 提交到数据库执行
   db.commit()
except:
   # 发生错误时回滚
   db.rollback()
 
# 关闭数据库连接
db.close()

1.5.删除数据

import pymysql
 
# 打开数据库连接
db = pymysql.connect("数据库IP地址","用户名","密码","数据库" )
 
# 使用cursor()方法获取操作游标 
cursor = db.cursor()
 
# SQL 删除语句
sql = "DELETE FROM EMPLOYEE WHERE AGE > %s" % (20)
try:
   # 执行SQL语句
   cursor.execute(sql)
   # 提交修改
   db.commit()
except:
   # 发生错误时回滚
   db.rollback()
 
# 关闭连接
db.close()

1.6.执行事务

# SQL删除记录语句
sql = "DELETE FROM EMPLOYEE WHERE AGE > %s" % (20)
try:
   # 执行SQL语句
   cursor.execute(sql)
   # 向数据库提交
   db.commit()
except:
   # 发生错误时回滚
   db.rollback()

1.7.读取数据库表数据并写入excel

import pymysql,xlwt

def export_excel(table_name):
	conn = pymysql.connect("数据库IP地址","用户名","密码","数据库" )
    cur = conn.cursor()

    sql = 'select * from %s;' %table_name

    #读取数据
    cur.execute(sql)
    fileds = [filed[0] for filed in cur.description]
    #所有数据
    all_date = cur.fetchall() 
    for result in all_date:
        print(result)

    #写excel

    book = xlwt.Workbook() #创建一个book

    sheet = book.add_sheet('result') #创建一个sheet表

    for col,filed in enumerate(fileds):
        sheet.write(0,col,filed)

    #从第一行开始写
    row = 1
    for data in all_date:
        for col,filed in enumerate(data):
            sheet.write(row,col,filed)
        row += 1

    book.save('%s.xls' %table_name)
	pass
    export_excel('stocks')

1.8.读取excel数据并写入数据库表

import pymysql
import xlrd
conn = pymysql.connect("数据库IP地址","用户名","密码","数据库" )
cursor = conn .cursor()

#读取excel数据写入数据库
book = xlrd.open_workbook("students.xls")
sheet = book.sheet_by_name('Sheet1')
query = 'insert into student_tbl (name, sex, minzu, danwei_zhiwu, phone_number, home_number) values (%s, %s, %s, %s, %s, %s)'
for r in range(1, sheet.nrows):
      name = sheet.cell(r,0).value
      sex = sheet.cell(r,1).value
      minzu = sheet.cell(r,2).value
      danwei_zhiwu = sheet.cell(r,3).value
      phone_number = sheet.cell(r,4).value
      home_number = sheet.cell(r,5).value
      values = (name, sex, minzu, danwei_zhiwu, phone_number, home_number)
      # 执行sql语句
      # 往SQL添加一条数据
      cursor.execute(query , values) 
print(values)
cursor.close()
db.commit()
db.close()

2.Python人机交互(Tkinter图形界面开发)

2.1.创建root窗口

#导入Tkinter包全部内容
from tkinter import *
#Tkinter根窗口实例化
root = Tk()
#设置窗口标题
root.title("my_Title")

2.2.控件布局

#设置label控件
label1 = Label(root,text = 'Number:')
label1.grid(row = 0, column = 0)
#设置text控件
text1 = Text(root,width = 30 , height = 1)
text1.grid(row = 1, column = 0)

2.3.实现commend

#设置调用函数
def myCalculate():
    a = int(text1.get("1.0",END))#从头开始取到结尾
    sum = a * 3
    text2.delete('1.0',END)
    text2.insert(INSERT,sum)
    pass
#设置Button
button = Button(root,text="click sum",command = myCalculate)
button.grid(row = 4, column = 0)

2.4.简单测试案例

#导入Tkinter包全部内容
from tkinter import *
#Tkinter根窗口实例化
root = Tk()
#设置窗口标题
root.title("my_Title")
#设置label控件
label1 = Label(root,text = 'Number:')
label1.grid(row = 0, column = 0)
#设置text控件
text1 = Text(root,width = 30 , height = 1)
text1.grid(row = 1, column = 0)
#设置label控件
label2 = Label(root,text = 'Sum:')
label2.grid(row = 2, column = 0)
#设置text控件
text2 = Text(root,width = 30 , height = 1)
text2.grid(row = 3, column = 0)
#设置调用函数
def myCalculate():
    a = int(text1.get("1.0",END))#从头开始取到结尾
    sum = a * 3
    text2.delete('1.0',END)
    text2.insert(INSERT,sum)
    pass
#设置Button
button = Button(root,text="click sum",command = myCalculate)
button.grid(row = 4, column = 0)

mainloop()
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

LetsonH

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值