python连接mysql

第一步:

        在PyCharm Community 创建flask项目,点击设置,搜索flask,pymysql加入。

第二步:

        目录如下python连接mysql_第1张图片

DB_TEST:
import pymysql
class DB_TEST:
    # 数据增删改
    def cud(sql):
        db = pymysql.connect(host="--", user="root", password="123456", database="mysql", charset="utf8")
        # 获取下标
        cursor = db.cursor()
        try:
            cursor.execute(sql)
            db.commit()
            return True
        except:
            db.rollback()
            db.close()
            return False
    # 数据查询
    def select(sql):
        db = pymysql.connect(host="--", user="root", password="123456", database="mysql", charset="utf8")
        # 获取下标
        cursor = db.cursor()
        try:
            cursor.execute(sql)
            # 查询
            result = cursor.fetchall()
            db.commit()
            return result
        except:
            db.rollback()
            db.close()




用的mysql自带的表

python连接mysql_第2张图片

 app:(测试mysql)


from flask import Flask, render_template, make_response, request, jsonify
import json
from model.DB_TEST import DB_TEST

app = Flask(__name__)

@app.route("/indexhtml")
def index():
    return render_template('index.html')

@app.route('/selectUsers', methods=['get'])
def select():
    sql = "select * from help_category"
    list = DB_TEST.select(sql)
    row_headers = [x[0] for x in list]
    json_data = []
    for result in list:
        json_data.append(dict(zip(row_headers, result)))
    return json.dumps(json_data)


@app.route('/addUsers', methods=['post'])
def update():
    sql = "update books set title='语文11111111' where id=1"
    print(u'結果', DB_TEST.cud(sql))



if __name__ == '__main__':
    app.run(host='0.0.0.0', port=5000, debug = True)
    # select()
    # pass

python连接mysql_第3张图片

测试sqlserver:

test库自己添加几条数据

CREATE TABLE [dbo].[books] (
  [id] int  NULL,
  [name] varchar(255) COLLATE Chinese_PRC_CS_AI_WS  NULL,
  [age] int  NULL
)  
ON [PRIMARY]
GO

ALTER TABLE [dbo].[books] SET (LOCK_ESCALATION = TABLE)

test1:

import pymssql 
from flask import Flask, render_template, make_response, request, jsonify
import json
server = "--"    # 连接服务器地址
user = "sa"                  # 连接帐号
password = "Sap123456789"     # 连接密码
conn = pymssql.connect(server, user, password, "test",charset='cp936')  #获取连接
cursor = conn.cursor() # 获取光标

app = Flask(__name__)

@app.route('/select', methods=['get'])
def select():
    # # 查询数据
    cursor.execute('SELECT * FROM books')
    jsonData = []
    rows = cursor.fetchall()
    for row in rows:
        result={}
        result['id']=row[0]
        result['name']=row[1]
        result['age']=row[2]
        jsonData.append(result)
    return json.dumps(jsonData,ensure_ascii=False)
if __name__ == '__main__':
    app.run(host='0.0.0.0', port=5000, debug=True)
    select()

python连接mysql_第4张图片

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