简体   繁体   English

在Resultset Java中执行Access Query

[英]Execute Access Query in Resultset Java

I am trying to execute count query on MDB file, and want to store it to a local variable. 我试图在MDB文件上执行计数查询,并希望将其存储到本地变量。

I am getting error "Type mismatch: cannot convert from boolean to int" if assign the output directly. 我收到错误“类型不匹配:如果直接分配输出,则无法从布尔值转换为int”。

While trying to use result set I am getting similar error as well "Type mismatch: cannot convert from boolean to ResultSet" 在尝试使用结果集时,我也遇到类似的错误“类型不匹配:无法从布尔值转换为ResultSet”

Here's the code: 这是代码:

String connectionString ="jdbc:odbc:Driver={Microsoft Access Driver (*.mdb)}; DBQ=C:\\test\\TestEJFolder\\BWC_Ejournal.mdb;";

        DriverManager.getConnection(connectionString, "", "");

        Connection conn = DriverManager.getConnection(connectionString, "", "");
        Connection conn1 = DriverManager.getConnection(connectionString, "", "");
        Connection conn2 = DriverManager.getConnection(connectionString, "", "");

        String sql = "SELECT * FROM Events";
        String dt = "SELECT TOP 1 [Date] FROM Events";
        String count = "SELECT COUNT(ID) FROM Events";

        Statement cmd = conn.createStatement(); 
        Statement cmd1 = conn1.createStatement();   
        Statement cmd2 = conn2.createStatement();   

        cmd.execute(sql);
        cmd1.execute(dt);
        cmd2.execute(count);

        ResultSet rc = cmd2.execute(count);

        int r_count = cmd2.execute(count);

Need help to fix this. 需要帮助来解决这个问题。

Bad code in too many ways. 糟糕的代码有很多种方式。 Start reading the JDBC tutorial . 开始阅读JDBC教程

Try something like this: 尝试这样的事情:

ResultSet rc = cmd2.execute(count);
int r_count = 0;
while (rc.next()) {
    r_count = rc.getInt(1);
}

You aren't closing any of your JDBC resources, which will only come to grief. 您没有关闭任何JDBC资源,这只会让您感到悲伤。

You should externalize your connection information. 您应该外部化您的连接信息。

I'd encapsulate more of your stuff into small, isolated methods rather than jumbling multiple statements together this way. 我将更多的东西封装成小的,孤立的方法,而不是用这种方式混合多个语句。

You ought to think about a well-defined, interface-based persistence layer. 您应该考虑一个定义明确,基于接口的持久层。

Make those SQL queries private static final String . 使这些SQL查询成为private static final String No need for them to be local. 他们不需要本地化。

I'd recommend that you try something more like this. 我建议你尝试更像这样的东西。 Start with an interface: 从界面开始:

package persistence;

import java.util.List;
import java.util.Map;

/**
 * EventDao
 * @author Michael
 * @link http://stackoverflow.com/questions/5016730/creating-a-dsn-less-connection-for-ms-access-within-java
 * @since 6/25/13 5:19 AM
 */
public interface EventDao {
    List<Map<String, Object>> findAllEvents();
}

Then write an implementation: 然后写一个实现:

package persistence;

import java.sql.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * EventDaoImpl
 * @author Michael
 * @link http://stackoverflow.com/questions/17213307/execute-access-query-in-resultset-java/17213356?noredirect=1#comment25072519_17213356
 * @since 6/25/13 5:15 AM
 */
public class EventDaoImpl implements EventDao {

    private static final String DEFAULT_URL = "jdbc:odbc:Driver={Microsoft Access Driver (*.mdb)}; DBQ=C:\\test\\TestEJFolder\\BWC_Ejournal.mdb;";
    private static final String SQL_FIND_ALL_EVENTS = "SELECT * FROM Events";

    private Connection connection;

    public EventDaoImpl(Connection connection) {
        this.connection = connection;
    }

    @Override
    public List<Map<String, Object>> findAllEvents() {
        List<Map<String, Object>> results = new ArrayList<Map<String, Object>>();
        Statement st = null;
        ResultSet rs = null;
        try {
            st = this.connection.createStatement();
            rs = st.executeQuery(SQL_FIND_ALL_EVENTS);
            results = map(rs);
        } catch (SQLException e) {
            e.printStackTrace();  
            throw new RuntimeException(e);
        } finally {
            close(rs);
            close(st);
        }
        return results;
    }

    public static Connection createConnection(String driver, String url, String username, String password) throws ClassNotFoundException, SQLException {
        Class.forName(driver);
        if ((username == null) || (password == null) || (username.trim().length() == 0) || (password.trim().length() == 0)) {
            return DriverManager.getConnection(url);
        } else {
            return DriverManager.getConnection(url, username, password);
        }
    }

    public static void close(Connection connection) {
        try {
            if (connection != null) {
                connection.close();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }


    public static void close(Statement st) {
        try {
            if (st != null) {
                st.close();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    public static void close(ResultSet rs) {
        try {
            if (rs != null) {
                rs.close();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    public static void rollback(Connection connection) {
        try {
            if (connection != null) {
                connection.rollback();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    public static List<Map<String, Object>> map(ResultSet rs) throws SQLException {
        List<Map<String, Object>> results = new ArrayList<Map<String, Object>>();
        try {
            if (rs != null) {
                ResultSetMetaData meta = rs.getMetaData();
                int numColumns = meta.getColumnCount();
                while (rs.next()) {
                    Map<String, Object> row = new HashMap<String, Object>();
                    for (int i = 1; i <= numColumns; ++i) {
                        String name = meta.getColumnName(i);
                        Object value = rs.getObject(i);
                        row.put(name, value);
                    }
                    results.add(row);
                }
            }
        } finally {
            close(rs);
        }
        return results;
    }

    public static List<Map<String, Object>> query(Connection connection, String sql, List<Object> parameters) throws SQLException {
        List<Map<String, Object>> results = null;
        PreparedStatement ps = null;
        ResultSet rs = null;
        try {
            ps = connection.prepareStatement(sql);

            int i = 0;
            for (Object parameter : parameters) {
                ps.setObject(++i, parameter);
            }
            rs = ps.executeQuery();
            results = map(rs);
        } finally {
            close(rs);
            close(ps);
        }
        return results;
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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