python的mysql模块使用

PyMySQL 安装

  • 在使用 PyMySQL 之前,我们需要确保 PyMySQL 已安装。
    PyMySQL 下载地址:https://github.com/PyMySQL/PyMySQL
  • 如果还未安装,我们可以使用以下命令安装最新版的 PyMySQL:
    $ pip install PyMySQL
    如果你的系统不支持 pip 命令,可以使用以下方式安装:
    使用 git 命令下载安装包安装(你也可以手动下载):
$ git clone https://github.com/PyMySQL/PyMySQL
$ cd PyMySQL/
$ python3 setup.py install

数据库连接

  • 连接数据库前,请先确认一下事项:
    1.创建了数据库testdb
    2.创建了一张表test
    3.链接数据库的testdb使用用户名root,密码123456,
    4.机器已经安装python的mysqldb模块

  • 实例

mysql> create database testdb;
Query OK, 1 row affected (0.00 sec)

mysql> use testdb;
Database changed
mysql> create table testtable(id int ,username char(20));
Query OK, 0 rows affected (0.01 sec)
mysql> insert into testtable values(20,'shan');
Query OK, 1 row affected (0.00 sec)

mysql> insert into testtable values(40,'wu');
Query OK, 1 row affected (0.00 sec)

mysql> select * from testtable;
+------+----------+
| id   | username |
+------+----------+
|   10 | shanwu   |
|   20 | shan     |
|   40 | wu       |
+------+----------+
3 rows in set (0.00 sec)

import pymysql

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

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

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

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

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

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

#输出
[root@shanwu python]# python3 db.py 
Database version : 5.6.36 
  • 使用类的方法db连接例子
#!/usr/bin/env python
import pymysql

class TestMysql(object):
    def __init__(self):
        self.dbConfig = {
            "host": "127.0.0.1",
            "port": 3306,
            "user": "root",
            "passwd": "123456",
            "db": "testdb"
        }
        conn = pymysql.connect(**self.dbConfig)
        self.a = conn


    def select(self):
        print("select")

    def update(self):
        print("update")





if __name__ == '__main__':
    conn = TestMysql()

猜你喜欢

转载自blog.csdn.net/wushan1992/article/details/80213612
今日推荐