Python3.6连接Mysql

Python3安装模块

pip3.6 install pymysql

1、Python3查询数据

import sys
import pymysql
# 打开数据库连接
db = pymysql.connect("10.0.0.101","root","123456","test" ,charset='utf8')

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

# SQL 查询语句
sql = "SELECT * FROM student"
try:
    # 执行SQL语句
    cursor.execute(sql)
    # 获取所有记录列表
    results = cursor.fetchall()
    print(results)
    print(len(results[0]))
    for row in results:
        sid = row[0]
        gender = row[1]
        class_id=row[2]
        sname=row[3]
        # 打印结果
        print("id是:%s,性别:%s,班级编号:%s,姓名:%s" %(sid, gender,class_id,sname ))
    # print(results)
except:
    print("Error: unable to fetch data")

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

 

2、Python插入数据代码

# -*- coding: utf-8 -*-
__author__ = 'chenruixuan'
import pymysql

# # 打开数据库连接
class MySql(object):
    def __init__(self,ip,user_name,passwd,db, char='utf8'):
        self.ip = ip
        # self.port = port
        self.username=user_name
        self.passwd=passwd
        self.mysqldb=db
        self.char=char

        self.MySQL_db = pymysql.connect(
            host=self.ip,
            user=self.username,
            passwd=self.passwd,
            db=self.mysqldb,
            charset=self.char)

    def Sql_exe(self,sql):
        cursor = self.MySQL_db.cursor()
        MySQL_sql = sql
        try:
            # 执行SQL语句
            cursor.execute(MySQL_sql)
            self.MySQL_db.commit()
        except:
            print("Error: unable to fetch data")
            self.MySQL_db.close()
        self.MySQL_db.close()

    # MySql_t=MySql("10.0.0.101","sheng","123456","Sheng_DB",char='utf8' )
MySql_t=MySql("10.0.0.101","novel","123456","Novel",char='utf8' )  #Novel
#
sql="insert into Novel(name,conext) values('name_t','connent_t')"
MySql_t.Sql_exe(sql)

 

3、修改数据库:

import pymysql  
  
# 打开数据库连接(ip/数据库用户名/登录密码/数据库名)  
db = pymysql.connect("localhost", "root", "root", "test")  
# 使用 cursor() 方法创建一个游标对象 cursor  
cursor = db.cursor()  
  
# SQL 更新语句  
sql = "UPDATE user SET name = 'Bob' WHERE id = 1"  
try:  
    # 执行SQL语句  
    cursor.execute(sql)  
    # 提交到数据库执行  
    db.commit()  
except:  
    # 发生错误时回滚  
    db.rollback()  
     
# 关闭数据库连接  
db.close()

 

4、修改数据库

import pymysql  
  
# 打开数据库连接(ip/数据库用户名/登录密码/数据库名)  
db = pymysql.connect("localhost", "root", "root", "test")  
# 使用 cursor() 方法创建一个游标对象 cursor  
cursor = db.cursor()  
  
# SQL 删除语句  
sql = "DELETE FROM user WHERE id  = 1"  
try:  
    # 执行SQL语句  
    cursor.execute(sql)  
    # 提交修改  
    db.commit()  
except:  
    # 发生错误时回滚  
    db.rollback()  
  
# 关闭数据库连接  
db.close()

 

原文链接:,转发请注明来源!

发表评论