Python3 MySQL 数据库连接

Python2 MySQL 数据库连接

centos7本身自带的2.7.5

[sy@sy-pc ~]$ python -V
Python 2.7.5

下载MySQLdb


centos准备:
# yum install mysql-devel python-devel gcc  libffi-devel openssl-devel


解压MySQLdb1-master.zip

#unzip MySQLdb1-master.zip
进入解压后的文件夹:
#cd MySQLdb1-master
先build  ,再install
先编译:
# /usr/bin/python2.7 /home/sy/Downloads/MySQLdb1-master/setup.py build
running build
running build_py
copying MySQLdb/release.py -> build/lib.linux-x86_64-2.7/MySQLdb
running build_ext
building '_mysql' extension
gcc -pthread -fno-strict-aliasing -O2 -g -pipe -Wall -Wp,-D_FORTIFY_SOURCE=2 -fexceptions -fstack-protector-strong --param=ssp-buffer-size=4 -grecord-gcc-switches -m64 -mtune=generic -D_GNU_SOURCE -fPIC -fwrapv -DNDEBUG -O2 -g -pipe -Wall -Wp,-D_FORTIFY_SOURCE=2 -fexceptions -fstack-protector-strong --param=ssp-buffer-size=4 -grecord-gcc-switches -m64 -mtune=generic -D_GNU_SOURCE -fPIC -fwrapv -fPIC -Dversion_info=(1,2,4,'final',1) -D__version__=1.2.4 -I/usr/include/mysql -I/usr/include/python2.7 -c _mysql.c -o build/temp.linux-x86_64-2.7/_mysql.o
gcc -pthread -shared -Wl,-z,relro build/temp.linux-x86_64-2.7/_mysql.o -L/usr/lib64/mysql -L/usr/lib64 -lmysqlclient -lpthread -lz -lm -lssl -lcrypto -ldl -lpython2.7 -o build/lib.linux-x86_64-2.7/_mysql.so
再安装:
[root@sy-pc MySQLdb1-master]# /usr/bin/python2.7 /home/sy/Downloads/MySQLdb1-master/setup.py install
ok。

mysql.py
#!/usr/bin/python
# -*- coding: UTF-8 -*-

import MySQLdb

# 打开数据库连接
db = MySQLdb.connect("192.168.55.180","root","root","test" )
#或者有下面这句
#db = MySQLdb.connect(host='192.168.55.180',port = 3306,user='root',passwd='root',db ='test' ,charset='utf8',)
# 使用cursor()方法获取操作游标
cursor = db.cursor()

# 使用execute方法执行SQL语句
cursor.execute("SELECT VERSION()")

# 使用 fetchone() 方法获取一条数据库。
data = cursor.fetchone()

print "Database version : %s " % data

# 关闭数据库连接
db.close()

运行结果:
# python mysql.py 
Database version : 5.6.35


Python3 MySQL 数据库连接

在使用 PyMySQL 之前,我们需要确保 python3 已安装
下载Python3
如:Python-3.6.2.tar.xz
解压:
# xz -d Python-3.6.2.tar.xz
# tar -xvf  Python-3.6.2.tar
进入解压后的目录
# cd Python-3.6.2
安装:
# ./configure --prefix=/home/sy/local/python3.6.2  --enable-optimizations
# make && make install
软连接:
# ln -s  /home/sy/local/python3.6.2/bin/python3  /usr/bin/python3
ln -s  真实文件  超链接文件
查看python3的版本
# python3  -V
Python 3.6.2


PyMySQL 下载地址:https://github.com/PyMySQL/PyMySQL   如:PyMySQL-master.zip
解压后安装步骤:
# unzip PyMySQL-master.zip

①进入解压后的文件夹

# cd PyMySQL-master

②输入安装命令

Windows命令行 
C:\Users\suyang\AppData\Local\Programs\Python\Python36\python.exe  setup.py  install
Linux命令行  
python3的安装目录可能不一样,
# /usr/bin/python3  /home/sy/Downloads/PyMySQL-master/setup.py  install
# /home/sy/local/python3.6.2/bin/python3  /home/sy/Downloads/PyMySQL-master/setup.py  install
Installed /home/sy/local/python3.6.2/lib/python3.6/site-packages/PyMySQL-0.7.11-py3.6.egg
Processing dependencies for PyMySQL==0.7.11
Finished processing dependencies for PyMySQL==0.7.11

案例:参考:http://www.runoob.com/python3/python3-mysql.html
案例:查看数据库版本
import pymysql

# 打开数据库连接
db = pymysql.connect(
        host='localhost',
        port = 3308,
        user='root',
        passwd='root',
        db ='test', 
	charset='utf8')

# 使用 cursor() 方法创建一个游标对象 cursor
cursor = db.cursor()

# 使用 execute()  方法执行 SQL 查询
cursor.execute("SELECT VERSION()")

# 使用 fetchone() 方法获取单条数据.
data = cursor.fetchone()

print ("Database version : %s " % data)

# 关闭数据库连接
db.close()

案例:新建表
import pymysql

# 打开数据库连接
db = pymysql.connect(
        host='localhost',
        port = 3308,
        user='root',
        passwd='root',
        db ='test', )

# 使用 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()

案例:插入数据
import pymysql

# 打开数据库连接
db = pymysql.connect(
    host='localhost',
    port=3308,
    user='root',
    passwd='root',
    db='test', )

# 使用 cursor() 方法创建一个游标对象 cursor
cursor = db.cursor()

# SQL 插入语句
sql = """INSERT INTO EMPLOYEE(FIRST_NAME,
         LAST_NAME, AGE, SEX, INCOME)
         VALUES ('Linux', 'Mohan', 20, 'M', 2000)"""
try:
    # 执行sql语句
    cursor.execute(sql)
    # 提交到数据库执行
    db.commit()
except:
    # 如果发生错误则回滚
    db.rollback()

# 关闭数据库连接
db.close()

案例:查询表
#!/usr/bin/python3

import pymysql

# 打开数据库连接
db = pymysql.connect(
        host='192.168.55.180',
        #host='127.0.0.1',
        port = 3306,
        user='root',
        passwd='root',
        db ='test',
        charset='utf8',)

# 使用 cursor() 方法创建一个游标对象 cursor
cursor = db.cursor()

sql = "SELECT * FROM `user`"
# 使用 execute()  方法执行 SQL 查询
try:
   # 执行SQL语句
   cursor.execute(sql)
   # 获取所有记录列表
   results = cursor.fetchall()
   for row in results:
      id = row[0]
      name = row[1]
      age = row[2]
      gender = row[3]
      year = row[4]
       # 打印结果
      print ("id=%d,name=%s,age=%d,gender=%s,year=%d" % \
             (id, name, age, gender, year ))
except:
   print ("Error: unable to fetch data")

# 使用 execute()  方法执行 SQL 查询
cursor.execute("SELECT VERSION()")
# 使用 fetchone() 方法获取单条数据.
data = cursor.fetchone()
print ("Database version : %s " % data)

# 关闭数据库连接
db.close()



end


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值