通过PyMySQL连接MySQL

安装PyMySQL

  • 点击开始按钮--运行--输入‘cmd’--输入命令‘pip install PyMySQL’自动下载安装
  • 	
    pip install PyMySQL

Python连接MySQL,先导入pymysql包

  • import pymysql

打开MySQL连接 主机地址(host) 端口号(port) 数据库名字(db) 用户名(user) 密码(password) 字符集编码(chareset)

  • db=pymysql.connect(host='127.0.0.1',
                       port=3306,
                       db='python3',
                       user='root',
                       password='123456',
                       charset='utf8')

数据库查询操作

  • Python查询MYSQL使用fetchone()方法获取单条数据,使用fetchall()方法获取多条数据
  • fetchone(sql):该方法获取下一个查询结果集,结果集是一个对象
  • fetchall():接受全部的返回结果行
  • rowcount():这是一个只读属性,并返回执行execute()方法后影响的行数
  • 输入sql语句 查询数据库内所有
  • sql='SELECT * FROM student'
  • 使用cursor()方法获取操作游标
  • cur=db.cursor()
  • 发送命令并返回结果,存储在游标中
  • cur.execute(sql)
  • fetchall()接受全部的返回结果行
  • rows=cur.fetchall()
    for r in rows:
        print('学号:{0}电话:{1}姓名:{2}性别:{3}'.format(r[0],r[1],r[2],r[3]))
    print('读取完毕')

例:创建注册页面

  • #导入pymysql包
    import pymysql
    
    #打开MySQL连接
    db=pymysql.connect(host='127.0.0.1',
                       port=3306,db='python3',
                       user='root',
                       password='123456',
                       charset='utf8')
    
    #用户输入 input()
    studentNo=input('请输入学号:')
    
    #检查学号是否存在
    sql='''
        SELECT studentName FROM python3.student WHERE studentNo={0}
    '''.format(studentNo)
    
    #使用cursor()方法获取操作游标
    cursor=db.cursor()
    
    #发送命令并返回结果,存储在游标中
    cursor.execute(sql)
    
    #获取下一个查询结果集,结果集是一个对象
    one_row=cursor.fetchone()
    
    #判断学号是否存在
    if one_row is not None:
        print('学号已存在,请重新输入...')
    else:
        studentName=input('请输入姓名:')
        loginpwd= input('请输入密码:')
        sex= input('请输入性别:')
        insert_sql='''
            INSERT INTO python3.student
                (studentNo,loginPwd,studentName,sex
               )
            VALUES (
                    '{0}',
                    '{1}',
                    '{2}',
                    '{3}'
                    );
        '''.format(studentNo,loginpwd,studentName,sex)
        try:
            cursor.execute(insert_sql)
            db.commit()
            print('新增成功...')
        except:
            print('新增失败...')

猜你喜欢

转载自my.oschina.net/u/3764483/blog/1805783