查询在 MySql 工作台中运行,但不在 Java eclipse 中运行

问题描述 投票:0回答:2

我创建了一个在 MySQL Workbench 中可以正常工作的查询,但是当我在 Eclipse 中运行它时却无法工作。与数据库的连接工作正常,因为通过更简单的查询,我得到了正确的结果。

java代码:

                String queryAlter = "SELECT count(*) ";
                queryAlter += "INTO @exist ";
                queryAlter += "FROM information_schema.columns ";
                queryAlter += "WHERE table_schema = database() ";
                queryAlter += "and COLUMN_NAME = 'question" + (100 + number + 1)+"' ";
                queryAlter += "AND table_name = '"+ tableName+"'; ";

                queryAlter += "set @query = IF(@exist <= 0, 'alter table "+ tableName+" add column question" + (100 + number + 1)+" varchar(2048) NULL', ";
                queryAlter += "'select \\'Column Exists\\' status'); ";
                queryAlter += "use joomla30; ";
                queryAlter += "prepare stmt from @query; ";

                queryAlter += "EXECUTE stmt;";

我收到这条消息:

发生错误。可能用户/密码无效 com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException:您的 SQL 语法有错误;检查与您的 MySQL 服务器版本相对应的手册,了解在 'set @query = IF(@exist <= 0, 'alter table n0x3c_twoquestions_table add column qu' at line 1

附近使用的正确语法)

查询字符串是:

 SELECT count(*) INTO @exist FROM information_schema.columns WHERE table_schema = database() and COLUMN_NAME = 'question101' AND table_name = 'n0x3c_twoquestions_table'; set @query = IF(@exist <= 0, 'alter table n0x3c_twoquestions_table add column question101 varchar(2048) NULL', 'select \'Column Exists\' status'); use joomla30; prepare stmt from @query; EXECUTE stmt;

我也在java中尝试过这个,我从MySQL查询在PhpMyAdmin中工作,但在JAVA Eclipse中不工作

                String s1 = "SELECT count(*) INTO @exist FROM information_schema.columns WHERE table_schema = database() and COLUMN_NAME = 'question" + (100 + number + 1)+"' AND table_name = '"+ tableName+"'; ";

                String s2 = "set @query = IF(@exist <= 0, 'alter table "+ tableName+" add column question" + (100 + number + 1)+" varchar(2048) NULL', 'select \\'Column Exists\\' status'); ";
                String s3 = "use joomla30; ";
                String s4 = "prepare stmt from @query; ";

                stmt.addBatch(s1);
                stmt.addBatch(s2);    
                stmt.addBatch(s3);   
                stmt.addBatch(s4);

                stmt.executeBatch();
                conn1.commit();

但是我有这个错误:

java.sql.BatchUpdateException:无法通过executeUpdate()发出SELECT。

java mysql eclipse mysql-workbench
2个回答
1
投票

您可以使用两个不同的查询。

首先是检查该列是否存在:

String countQuery = "select count(*) from information_schema.columns WHERE table_schema = database() and COLUMN_NAME = 'question106' and table_name='n0x3c_twoquestions_table'";

然后如果

countQuery
返回0,就可以执行
alterQuery
:

String alterQuery = "alter table n0x3c_twoquestions_table add column question106 varchar(2048) NULL";

如果你不想使用两个不同的查询,你可以通过异常捕获来处理:

String alterQuery = "alter table n0x3c_twoquestions_table add column question106 varchar(2048) NULL";
try (Connection conn = ds.getConnection(); PreparedStatement ps = conn.prepareStatement(alterQuery)) {
    ps.execute();
} catch (SQLException e) {
    if (e.getErrorCode() == 1060) {
        columnExists = true;
    } else {
        // TODO handle exception
    }
}

我找到了错误代码MySQL服务器错误代码


0
投票
@WebServlet("/uploadServlet")
@MultipartConfig(maxFileSize = 160000) // upload file's size up to 16MB /
                                            // 16000000 byte
public class FileUploadToDataBaseServlet extends HttpServlet {
    /*
     * FileUploadToDataBaseServlet:  files upload to database with Servlet, JSP
     * and MySQL. Creating MySQL database table. Coding upload form page. Coding
     * file upload servlet. Coding message page. Testing the application and
     * verifying file stored in database.
     */
    
    private String databaseURL = "jdbc:mysql://localhost:3306/MyDatabase";
    private String databaseUser = "root";
    private String databasePassWord = "2888";

    /*
     * This method is called by servlet service method to handle the POST
     * request from client. The HTTP POST method allows the client to send data
     * of unlimited length to the Web server a single time and is useful when
     * posting information to the server.
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        // gets values of text fields
        String firstName = request.getParameter("firstName");
        String lastName = request.getParameter("lastName");
        String phone = request.getParameter("phone");
        String email = request.getParameter("email");
        String country = request.getParameter("country");
        String photo = request.getParameter("photo");

        // InputStream's are used for reading byte based data
        InputStream inputStream = null; // input stream of the upload file

        // obtains the upload file part in this multipart request

        Part filePart = request.getPart("photo");
        if (filePart != null) {
            // prints out some information for debugging
            System.out.println(filePart.getName());
            System.out.println(filePart.getSize());
            System.out.println(filePart.getContentType());

            // obtains input stream of the upload file
            inputStream = filePart.getInputStream();
        }

        Connection connection = null; // connection to the database
        String message = null; // message will be sent back to client

        try {
            // connects to the database
            DriverManager.registerDriver(new com.mysql.jdbc.Driver());
            connection = DriverManager.getConnection(databaseURL, databaseUser, databasePassWord);

            // constructs SQL statement
            String sql = "INSERT INTO registration (first_name, last_name, phone, email, country, photo )"
                    + "values (?, ?, ?, ?, ?, ?)";

            // The performance of the application will be faster if you use
            // PreparedStatement,
            // which gives better performance than Statement class.

            PreparedStatement statement = connection.prepareStatement(sql);
            statement.setString(1, firstName);
            statement.setString(2, lastName);
            statement.setString(3, phone);
            statement.setString(4, email);
            statement.setString(5, country);

            if (inputStream != null) {
                // bring input stream of the upload file for the blob column
                statement.setBlob(6, inputStream);
            }

            // sends the statement to the database server
            int row = statement.executeUpdate();
            if (row > 0) {
                message = "File uploaded and saved into database";
            }
        } catch (SQLException exception) {
            message = "ERROR: " + exception.getMessage();
            exception.printStackTrace();
        } finally {
            if (connection != null) {
                // closes the database connection
                try {
                    connection.close();
                } catch (SQLException exception) {
                    exception.printStackTrace();
                }
            }
            // sets the message in request scope
            request.setAttribute("Message", message);

            // forwards message to the page
            getServletContext().getRequestDispatcher("/Alert.html").forward(request, response);
        }

    }
© www.soinside.com 2019 - 2024. All rights reserved.