Python3.6 连接MySQL操作

查看mysql数据库版本:

#-*-coding:utf-8-*-

import pymysql

# 打开数据库
db = pymysql.connect(
    host = '10.10.7.190',
    user = 'dba_admin',
    password = 'Dba_admin@hankyoon.com',
    port = 3306,
    database = 'yoon'
)

# 使用 cursor() 方法获取操作游标
cursor =  db.cursor()

# 使用exeute方式执行SQL语句
cursor.execute("select @@version")

# Python查询Mysql使用 fetchone() 方法获取单条数据, 使用fetchall() 方法获取多条数据。
result = cursor.fetchone()

print(result)

#关闭数据库
db.close()

连接mysql数据库插入一条数据:

#-*-coding:utf-8-*-

import pymysql

# 打开数据库
db = pymysql.connect(
    host = '10.10.7.190',
    user = 'dba_admin',
    password = 'Dba_admin@hankyoon.com',
    port = 3306,
    database = 'yoon'
)

# 使用 cursor() 方法获取操作游标
cursor =  db.cursor()

# SQL 插入
sql = "insert into hank values (777,'vvv')"

try:
    # 执行sql
    cursor.execute(sql)
    db.commit()
except:
    # 错误回滚
    db.rollback()

#关闭数据库
db.close()

mysql 执行 select * from table 显示所有内容:

#-*-coding:utf-8-*-

import pymysql

# 打开数据库
db = pymysql.connect(
    host = '10.10.7.190',
    user = 'dba_admin',
    password = 'Dba_admin@hankyoon.com',
    port = 3306,
    database = 'yoon'
)

# 使用 cursor() 方法获取操作游标
cursor =  db.cursor()

# SQL查询语句
sql = "select * From hank"

try:
    # 执行SQL 语句
    cursor.execute(sql)
    # 获取所有表记录列表
    result = cursor.fetchall()
    for row in result:
        id = row[0]
        name = row[1]
        # 打印结果
        print("id=%d,name=%s" %(id,name))
except:
    print("error")

#关闭数据库
db.close()

 

posted @ 2022-04-20 14:23  __Yoon  阅读(76)  评论(0编辑  收藏  举报