【问题标题】:Create Table in MySql from User Input Value根据用户输入值在 MySql 中创建表
【发布时间】:2014-01-22 18:08:04
【问题描述】:

我正在尝试在 MySQL 数据库中创建一个表,其中没有字段是可变的并且它们的大小是恒定的。是否可以根据用户输入值创建数据库?

我已经创建了两个 JSP 文件

readData.jsp

<form method="post" action="makeDB.jsp" name="testForm">        

        Name <input class="input_txt" id="surName" name="surName" type="text" maxlength="30">                           
        Type <select id="mySelect"  name="surType">
                <option>Choose one:</option>
                <option>Voting</option>
                <option>Application</option>
                <option>Invitation</option>                         
            </select>               
        Description<textarea class="input_txt" id="surDescrip" name="surDescrip" rows="2" cols="30" maxlength="1200">
        </textarea>

        Question <input class="input_txt" id="Ques" name="Ques" type="text" maxlength="1020"><br /><br />
            Answer Option 1 : <input class="input_txt" id="opt1" name="AnsOption1" type="text" maxlength="100"><br />
            Answer Option 2 : <input class="input_txt" id="opt2" name="AnsOption2" type="text" maxlength="100"><br />
            Answer Option 3 : <input class="input_txt" id="opt3" name="AnsOption3" type="text" maxlength="100"><br />
            Answer Option 4 : <input type="hidden" id="OptionCount" name="OptionCount">


        <input id="sub" type="submit" value="Start Creating DB">

</form>

ma​​keDB.jsp

<%!
    // Variables 
    Connection conn = null;
    Statement stmt = null;      
    static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
    static final String DB_URL = "jdbc:mysql://localhost/crDB";
    static final String USER_NM = "foo";
    static final String PASS_WRD = "bar";
    static final String MyDB_Name = "Something";

    public void makeDB(String MyDB_Name, String SURVEY_NAME, String SURVEY_TYPE, String SURVEY_DESCRIPTION, String QUESTION, String ANS1, String ANS2, String ANS3) {

    try {

            Class.forName(JDBC_DRIVER);
            conn = DriverManager.getConnection(DB_URL, USER_NM, PASS_WRD);
            stmt = conn.createStatement();
            String query = "CREATE TABLE "+MyDB_Name+" ("+SURVEY_NAME+")........."; 
            stmt.executeUpdate(query);

            stmt.close();
            conn.close();

        }  catch (Exception e) {

            //Handle errors for Class.forName
            e.printStackTrace();    
        }    

    } 

%>

【问题讨论】:

  • 是的,有可能,你的代码有什么问题?

标签: java mysql database jsp


【解决方案1】:

创建表不是别的东西,它也是一个简单的 sql 查询,就像任何其他 select/update 查询一样,您只需执行该查询即可。

更多地查看prepared statement 并使用它。不要像那样执行普通的 sql 查询它可能会导致 sql 注入。

【讨论】:

猜你喜欢
  • 1970-01-01
  • 2021-08-20
  • 2014-11-16
  • 1970-01-01
  • 1970-01-01
  • 2015-02-01
  • 1970-01-01
  • 2016-02-12
  • 2018-03-12
相关资源
最近更新 更多