python3 连接mysql

参考了帖子

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]$

你可能感兴趣的:(mysql,python)