python连接数据库

Python中“if name==‘main’:”

学过Java、C、C++的程序员应该都知道,每次开启一个程序,都必须写一个主函数作为程序的入口,也就是我们常说的main函数。如下所示, main()就是Java中的一个main函数。

public class HelloWorld {
public static void main(String[] args) {

    System.out.println("HelloWorld");

}
}

与Java、C、C++等几种语言不同的是,Python是一种解释型脚本语言,在执行之前不同要将所有代码先编译成中间代码,Python程序运行时是从模块顶行开始,逐行进行翻译执行,所以,最顶层(没有被缩进)的代码都会被执行,所以Python中并不需要一个统一的main()作为程序的入口。在某种意义上讲,“if namemain:”也像是一个标志,象征着Java等语言中的程序主入口,告诉其他程序员,代码入口在此——这是“if namemain:”这条代码的意义之一。1. __name__的理解1.1 为什么使用__name__属性?Python解释器在导入模块时,会将模块中没有缩进的代码全部执行一遍(模块就是一个独立的Python文件)。开发人员通常会在模块下方增加一些测试代码,为了避免这些测试代码在模块被导入后执行,可以利用__name__属性。1.2 __name__属性。name__属性是Python的一个内置属性,记录了一个字符串。若是在当前文件,name 是__main。在hello文件中打印本文件的__name__属性值,显示的是__main__表示作为当前文件被执行

在这里插入图片描述

若是导入的文件,__name__是模块名。test文件导入hello模块,在test文件中打印出hello模块的__name__属性值,显示的是hello模块的模块名。
在这里插入图片描述

因此__name__ == ‘main’ 就表示在当前文件中,可以在if name == ‘main’:条件下写入测试代码,如此可以避免测试代码在模块被导入后执行。

安装pymsql

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
将版本输出到该文件
在这里插入图片描述
在这里插入图片描述
将文件所有依赖性安装
在这里插入图片描述

增加

import pymysql



def main():
    #1、连接数据库(主机,端口,用户名,密码,数据库名,字符集)
    conn=pymysql.connect(host='127.0.0.1',port=3306,user='root',passwd='root',db='hrs',charset='utf8')
    # print(conn)
    #2.通过游标发送sql语句
    #with上下文语法会根据上下文自动关闭,否则需要手动关,cursor.close()
    try:#如果成功则提交事务,失败则回滚
        with conn.cursor() as cursor:
            result=cursor.execute('insert into tb_dept values(90,"销售2部","重庆")')
            if result==1:
                print('添加成功')
                conn.commit()
    except pymysql.MySQLError as error:
        print('添加失败')
        print(error)
        conn.rollback()
    finally:
        conn.close()
if __name__=='__main__':
    main()


删除

import pymysql

def main():
    no=input('请输入要删除的部门编号:')
    conn=pymysql.connect(host='127.0.0.1',port=3306,user='root',passwd='root',db='hrs',charset='utf8')
    try:
        with conn.cursor() as cursor:
            result=cursor.execute(
                'delete from tb_dept where dno=%s'%(no))
            if result==1:
                print('删除成功')
                conn.commit()
            else:
                print('删除失败')
                conn.rollback()
    except pymysql.MySQLError as error:
        print('异常')
        print(error)
        conn.rollback()
    finally:
        conn.close()

if __name__ == '__main__':
    main()

修改

import pymysql

def main():

    no=input('请输入要编辑的部门编号:')
    loc=input('部门的新地址:')
    print('update tb_dept set dloc=%s where dno=%s'%(loc,no))
    conn=pymysql.connect(host='127.0.0.1',port=3306,user='root',passwd='root',db='hrs',charset='utf8')
    try:
        with conn.cursor() as cursor:
            #这是execute函数的一个格式,用逗号,而不是%
            result=cursor.execute(
                'update tb_dept set dloc=%s where dno=%s',(loc,no))
            if result==1:
                print('更新成功')
                conn.commit()
            else:
                print('更新失败')
                conn.rollback()
    except pymysql.MySQLError as error:
        print('异常')
        print(error)
        conn.rollback()
    finally:
        conn.close()

if __name__ == '__main__':
    main()

查询

import pymysql

def main():
    conn=pymysql.connect(host='127.0.0.1',port=3306,user='root',passwd='root',db='hrs',charset='utf8')
    try:
        with conn.cursor() as cursor:
            cursor.execute(
                'select dno,dname,dloc from tb_dept')
            for row in cursor.fetchall():
                print(f'部门编号:{row[0]},部门名称:{row[1]},部门地址:{row[2]}')
                print('-'*20)


    except pymysql.MySQLError as error:
        print('异常')
        print(error)

    finally:
        conn.close()

if __name__ == '__main__':
    main()
import pymysql

def main():
    conn=pymysql.connect(host='127.0.0.1',port=3306,user='root',
                         passwd='root',db='hrs',charset='utf8',
                         cursorclass=pymysql.cursors.DictCursor)#设置为字典型游标
    try:
        with conn.cursor() as cursor:
            cursor.execute(
                'select dno as no,dname as name,dloc as location from tb_dept')
            # print(cursor.fetchone())
            # print(cursor.fetchmany(2))
            # print(cursor.fetchall())
            #字典项游标可以根据键取值
            for row in cursor.fetchall():
                print(row['no'],end='\t')
                print(row['name'],end='\t')
                print(row['location'])
        


    except pymysql.MySQLError as error:
        print('异常')
        print(error)

    finally:
        conn.close()

if __name__ == '__main__':
    main()
import pymysql

#部门类
class Dept(object):#父类是Object,可省
    def __init__(self,no,name,location):
        self.no=no
        self.name=name
        self.location=location
    def __str__(self):
        return f'{self.no}\t{self.name}\t{self.location}'

def main():
    conn=pymysql.connect(host='127.0.0.1',port=3306,user='root',
                         passwd='root',db='hrs',charset='utf8',
                         cursorclass=pymysql.cursors.DictCursor)#设置为字典型游标
    try:
        with conn.cursor() as cursor:
            cursor.execute('select dno as no,dname as name,dloc as location from tb_dept')
            for row in cursor.fetchall():
                dept=Dept(**row)#调用构造器,直接把字典转为对象。但是人家要的不是字典row
                #列表元组解包是一个*,字典是两个**
                print(dept)
    except pymysql.MySQLError as error:
            print(error)
    finally:
        conn.close()

if __name__=='__main__':
    main()
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值