python3 连接mysql

24 篇文章 0 订阅

参考了帖子

https://www.runoob.com/python3/python3-mysql.html

首先需要安装pymysql 模块

[root@rws1270149 /]# pip3 install pymysql
Collecting pymysql
  Downloading https://files.pythonhosted.org/packages/ed/39/15045ae46f2a123019aa968dfcba0396c161c20f855f11dea6796bcaae95/PyMySQL-0.9.3-py2.py3-none-any.whl (47kB)
    100% |████████████████████████████████| 51kB 9.5MB/s
Installing collected packages: pymysql
Successfully installed pymysql-0.9.3
You are using pip version 19.0.3, however version 19.1.1 is available.
You should consider upgrading via the 'pip install --upgrade pip' command.

一个简单的连接及查询版本的例子

[crsusr@rws1270149 python_study]$ cat mypy02.py
#!/usr/bin/python3.7
import sys,string,os,glob,time
#from os import *
import pymysql

mysql_conn = pymysql.connect('rws1270149','root','password','sampdb')
cursor = mysql_conn.cursor()
cursor.execute('select version()')
row = cursor.fetchone()
db.close()
print(row[0])

[crsusr@rws1270149 python_study]$ ./mypy02.py
5.7.25-log

练习了插入数据和查询数据的一个例子


    [crsusr@rws1270149 python_study]$ cat mypy02.py
#!/usr/bin/python3.7
import sys,string,os,glob,time
#from os import *
import pymysql

mysql_conn = pymysql.connect('rws1270149','root','password','sampdb')
cursor = mysql_conn.cursor()
cursor.execute('select version()')
cursor.execute('drop table if exists employee')
create_employee_stmt = """create table employee(
first_name char(20) not null,
last_name char(20),
age int,
sex char(1),
income float)"""
cursor.execute(create_employee_stmt)
try:
    cursor.execute('insert into employee(first_name,last_name,age,sex,income) values("wang","ying",88,"1",888888)')
    cursor.execute('insert into employee(first_name,last_name,age,sex,income) values("li","gang",77,"0",777777)')
    cursor.execute('insert into employee(first_name,last_name,age,sex,income) values("yang","li",66,"1",666666)')
    #cursor.execute('commit')
    mysql_conn.commit()
except:
    mysql_conn.rollback()

cursor.execute('select * from employee')
results = cursor.fetchall()
for row in results:
    first_name=row[0]
    last_name=row[1]
    age = row[2]
    if row[3]=='0':
        sex = 'female'
    elif row[3]=='1':
        sex = 'male'
    else:
        sex='unknown'
    income=row[4]
    print('first_name::',first_name,";",'last_name::',last_name,";",'age::',age,";",'sex::',sex,";",'income::',income,";")
mysql_conn.close()
#row = cursor.fetchone()
#print(row[0])

[crsusr@rws1270149 python_study]$ ./mypy02.py
first_name:: wang ; last_name:: ying ; age:: 88 ; sex:: male ; income:: 888888.0 ;
first_name:: li ; last_name:: gang ; age:: 77 ; sex:: female ; income:: 777777.0 ;
first_name:: yang ; last_name:: li ; age:: 66 ; sex:: male ; income:: 666666.0 ;
[crsusr@rws1270149 python_study]$

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值