简体   繁体   中英

How to create MySQL Procedures from java code when software runs for first time (Setting up database procedures))

I want to setup my database when my application runs on a new device for the first time. For this, I have to create necessary tables, stored procedures, etc. I successfully created tables on the initial start of the application. But I'm not able to implement the same for procedures.

I tried executing the stored procedure query when the application is started the first time. Although the MySQL code to create procedure is correct, Java gives an error saying
java.sql.BatchUpdateException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'DELIMITER // CREATE PROCEDURE update_registered_fields (IN _field VARCHAR(200))' at line 1 If I run the same query in MySQL webview it runs perfectly.

I have not shown the connection to the database here as it is working fine. And I have used procedures.xml file to get a query for the code.

DatabaseHandler.java

private static void inflateProcedure() throws SQLException, FileNotFoundException, ParserConfigurationException, SAXException, IOException{
    Set<String> set = new HashSet<>();
    List<String> procedureData = new ArrayList<>();
    String query = "SHOW PROCEDURE STATUS WHERE Db = '"+Preferences.getPreferences().getDatabaseName()+"';";
    System.out.println(query);
    stmnt = con.createStatement();
    ResultSet rs = stmnt.executeQuery(query);
    while(rs.next()){
        set.add(rs.getString("NAME").toLowerCase());
    }
    System.out.println("Already Loaded Procedures "+set);
    DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
    DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
    Document doc = dBuilder.parse(new FileInputStream(Preferences.getPreferences().getLocation()+"procedures.xml"));
    NodeList nList = doc.getElementsByTagName("table-entry");
    for (int i = 0; i < nList.getLength(); i++) {
        Node nNode = nList.item(i);
        Element entry = (Element) nNode;
        String procedureName = entry.getAttribute("name");
        String params = entry.getAttribute("params");
        String procedureQuery = entry.getAttribute("data");
        if (!set.contains(procedureName.toLowerCase())) {
            procedureData.add(String.format("DELIMITER // CREATE PROCEDURE %s %s \n"
                    + "BEGIN;\n"
                    + " %s \n"
                    + "END //\n DELIMITER ", procedureName, params, procedureQuery));
        }
    }
    if (procedureData.isEmpty()) {
        System.out.println("Procedures are already loaded");
    }
    else {
        System.out.println("Inflating new Procedures.");
        createProcedures(procedureData);
    }
}

private static void createProcedures(List<String> procedureData) throws SQLException{
    Statement statement = con.createStatement();
    for (String command : procedureData) {
        System.out.println(command);
        statement.addBatch(command);
    }
    statement.executeBatch();
    statement.close();
}

procedures.xml

<procedures>
<table-entry name="update_registered_fields" params="(IN _field VARCHAR(200))" data="DECLARE _value INT DEFAULT 0;

    SET _value := (SELECT `user_register_feilds`.`last_used` FROM `user_register_feilds` WHERE `user_register_feilds`.`name` = _field);
    UPDATE `user_register_feilds` SET `user_register_feilds`.`last_used` = _value+1 WHERE `user_register_feilds`.`name` = _field;"/>

<table-entry name="sort_fields" params="(IN _value INT(50))" data="SELECT * FROM user_enquiry ORDER BY last_used DESC, id ASC LIMIT _value;"/>

I want to execute this query. I have even tried allowMultiQueries . I also want to know is this the correct way to fill the database when we start the application for the first time.

You seem to have used delimiters in your sql query, that you're trying to run in JDBC, which is apparent from your error message: java.sql.BatchUpdateException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'DELIMITER // CREATE PROCEDURE update_registered_fields (IN _field VARCHAR(200))' at line 1 java.sql.BatchUpdateException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'DELIMITER // CREATE PROCEDURE update_registered_fields (IN _field VARCHAR(200))' at line 1 .

Try removing the delimiters. Delimiters are used in raw sql. JDBC doesn't need delimiters.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM