如何动态创建表列名称并使用flask和mysql插入值

时间:2017-10-26 07:06:14

标签: python mysql flask

我想基于特定文本框中给出的值创建多个文本框,另一个文本框将保存表名,现在我想从文本框中获取表名,并获取给出的值。多个文本框作为列名,应该在MySQL中创建一个数据库。

这是我的py

from flask import Flask
from flask import request
from flask import render_template
from flaskext.mysql import MySQL

app = Flask(__name__)


mysql = MySQL()
app.config['MYSQL_DATABASE_USER'] = 'root'
app.config['MYSQL_DATABASE_PASSWORD'] = 'root'
app.config['MYSQL_DATABASE_DB'] = 'matrimony'
app.config['MYSQL_DATABASE_HOST'] = 'localhost'
mysql.init_app(app)


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


@app.route('/searchQuery', methods=['POST'])
def search_query():
    if request.method: "POST"
    conn = mysql.connect()
    cursor = conn.cursor()
    name=request.form.get('name')
    sq_ = request.form.get('searchQuery')
    x=request.form.get('x')
    cursor.execute("""CREATE TABLE `%s`( NAME VARCHAR(50) DEFAULT NULL) """ % (name))
    print(sq_)

    return render_template('simplesearch.html', search_query=sq_)



if __name__ == '__main__':
    app.run() 

index1.html

<form action="{{ url_for('search_query') }}" method="post">
    Name:<input type="text"  name="name">
    Column Number:<input type="text" name="searchQuery" id="searchQuery"><input type="submit" value="Submit">
</form>

simplesearch.html

<table>
    {% for x in range(search_query | int) %}
        <tr>
            <td>
                <input type="text"  name="i{{ x }}">
                <input type="hidden" value="{{ search_query }}">
            </td>
        </tr>
    {% endfor %}
<input type="submit" value="Submit">
</table>

它从tex tbox中获取表名,只创建一列。 任何帮助都会非常感谢谢谢你

1 个答案:

答案 0 :(得分:2)

我假设您需要使用用户定义的字段创建动态MySQL表。您无需两次提交表单。使用jQuery的一些帮助创建动态字段。然后处理控制器中的值。

以下是一种可以完成此操作的方法,如下所示。该计划需要Flask-MySQL,可以使用pip install Flask-MySQL安装。

application.py

from flask import Flask
from flask import request
from flask import render_template
from flaskext.mysql import MySQL

app = Flask(__name__)


mysql = MySQL()
app.config['MYSQL_DATABASE_USER'] = 'root'
app.config['MYSQL_DATABASE_PASSWORD'] = 'root'
app.config['MYSQL_DATABASE_DB'] = 'matrimony'
app.config['MYSQL_DATABASE_HOST'] = 'localhost'
mysql.init_app(app)


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


@app.route('/create_table', methods=['POST'])
def create_table():
    if request.method=="POST":
        try:
            table_name = request.form.get('table_name')
            field_name_list = request.form.getlist('fields[]')
            field_list = []
            for field in field_name_list:
                field_list.append(field+ " VARCHAR(50) DEFAULT NULL")
            field_query = " ( " + ", ".join(field_list) + " ) "
            create_table_query = 'CREATE TABLE `'+table_name+'`' + field_query
            conn = mysql.connect()
            cursor = conn.cursor()
            cursor.execute(create_table_query)
            return "Table: "+table_name+" created successfully"
        except Exception as e:
            return str(e)

if __name__ == '__main__':
    app.run(debug = True) 

index1.html

<form action="{{ url_for('create_table') }}" method="post">
    Name:<input type="text" name="table_name" id="table_name" />
    Column Number:<input type="text" name="number_of_columns" id="number_of_columns" />
    <input type="button" id="generate_field_btn" value="Generate Field" />
    <div id="dynamic_field">

    </div>
    <input type="submit" name="Create Table">
</form>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script type="text/javascript">
    $(document).ready(function(){
        $("#generate_field_btn").on("click",function(){
            $number_of_columns = $("#number_of_columns").val();
            $number_of_columns = parseInt($number_of_columns);
            for($i=0; $i<$number_of_columns; $i++){
                $field_name = "Field "+($i+1)+": ";
                $new_element = $field_name+'<input type="text" name="fields[]"/><br/>';
                $("#dynamic_field").append($new_element);   
            }

        })
    })
</script>

<强>输出:

  1. 从用户处获取输入字段:
  2. Getting input fields from user

    1. 创建表格后显示成功消息:
    2. Showing success message after table creation

      1. 确保使用phpMyAdmin中的所需字段创建表:
      2. Ensure the table is created with desired fields from phpMyAdmin