-5

我有以下代码:

import java.sql.*;
import java.net.*;

public class binsz {

    public void dbConnect(String db_connect_string, String username, String password) {
        try {
            Class.forName("net.sourceforge.jtds.jdbc.Driver");
            Connection conn = DriverManager.getConnection(db_connect_string, username, password);
            // System.out.println("connected");
            }

        catch (Exception e) {
            e.printStackTrace();
            }
    }

    public void dbQuery(String query) {
        try {
            Statement stmt = conn.createStatement();
            ResultSet rs = stmt.executeQuery(query);
            }

        catch (Exception e) {
            e.printStackTrace();
            }

    }


    public static void main(String[] args) throws Exception {

        String db_name = "sqlserver.local";
        String username = "sa";
        String password = "passwordforsa";
        String connection = "jdbc:jtds:sqlserver://" + db_name;

        Connection conn = null;
        binsz db = new binsz();
        db.dbConnect(connection, username, password);
        String query = "SELECT TOP 2 * FROM aux..table_name";
        db.dbQuery(query);
    }

}

并在编译时出错:

binsz.java:20: cannot find symbol
symbol  : variable conn
location: class sip_bins
            Statement stmt = conn.createStatement();
                             ^
1 error

我如何使用binsz db = new binsz();它来执行查询并检索它的值。

谢谢

PS:与数据库的连接正在工作..(如果我取消注释该行,它会打印“已连接”)..

4

5 回答 5

1

这是非常糟糕的代码 - 编写时无用。你有很多工作要做。

我建议您研究一下并丢弃您的代码:

package persistence;

import java.sql.*;
import java.util.*;

/**
 * util.DatabaseUtils
 * User: Michael
 * Date: Aug 17, 2010
 * Time: 7:58:02 PM
 */
public class DatabaseUtils {
    private static final String DEFAULT_DRIVER = "oracle.jdbc.driver.OracleDriver";
    private static final String DEFAULT_URL = "jdbc:oracle:thin:@host:1521:database";
    private static final String DEFAULT_USERNAME = "username";
    private static final String DEFAULT_PASSWORD = "password";
/*
    private static final String DEFAULT_DRIVER = "org.postgresql.Driver";
    private static final String DEFAULT_URL = "jdbc:postgresql://localhost:5432/party";
    private static final String DEFAULT_USERNAME = "pgsuper";
    private static final String DEFAULT_PASSWORD = "pgsuper";
*/
/*
    private static final String DEFAULT_DRIVER = "com.mysql.jdbc.Driver";
    private static final String DEFAULT_URL = "jdbc:mysql://localhost:3306/party";
    private static final String DEFAULT_USERNAME = "party";
    private static final String DEFAULT_PASSWORD = "party";
*/

    public static void main(String[] args) {
        long begTime = System.currentTimeMillis();

        String driver = ((args.length > 0) ? args[0] : DEFAULT_DRIVER);
        String url = ((args.length > 1) ? args[1] : DEFAULT_URL);
        String username = ((args.length > 2) ? args[2] : DEFAULT_USERNAME);
        String password = ((args.length > 3) ? args[3] : DEFAULT_PASSWORD);

        Connection connection = null;

        try {
            connection = createConnection(driver, url, username, password);
            DatabaseMetaData meta = connection.getMetaData();
            System.out.println(meta.getDatabaseProductName());
            System.out.println(meta.getDatabaseProductVersion());

            String sqlQuery = "SELECT PERSON_ID, FIRST_NAME, LAST_NAME FROM PERSON ORDER BY LAST_NAME";
            System.out.println("before insert: " + query(connection, sqlQuery, Collections.EMPTY_LIST));

            connection.setAutoCommit(false);
            String sqlUpdate = "INSERT INTO PERSON(FIRST_NAME, LAST_NAME) VALUES(?,?)";
            List parameters = Arrays.asList("Foo", "Bar");
            int numRowsUpdated = update(connection, sqlUpdate, parameters);
            connection.commit();

            System.out.println("# rows inserted: " + numRowsUpdated);
            System.out.println("after insert: " + query(connection, sqlQuery, Collections.EMPTY_LIST));
        } catch (Exception e) {
            rollback(connection);
            e.printStackTrace();
        } finally {
            close(connection);
            long endTime = System.currentTimeMillis();
            System.out.println("wall time: " + (endTime - begTime) + " ms");
        }
    }

    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;
    }

    public static int update(Connection connection, String sql, List<Object> parameters) throws SQLException {
        int numRowsUpdated = 0;
        PreparedStatement ps = null;
        try {
            ps = connection.prepareStatement(sql);

            int i = 0;
            for (Object parameter : parameters) {
                ps.setObject(++i, parameter);
            }
            numRowsUpdated = ps.executeUpdate();
        } finally {
            close(ps);
        }
        return numRowsUpdated;
    }
}
于 2012-05-16T11:07:17.090 回答
0

Connection conn将当前在方法中的哪个声明dbConnect为实例变量。您收到此错误是因为conn在方法中是未知的dbQuery

于 2012-05-16T11:01:34.117 回答
0

您应该将连接设为实例变量this.conn = DriverManager...。我还建议使用一个好的连接池。

还记得在你完成它们之后关闭你的语句、结果集和连接。

更新

try {
    ...
} finally {
    if (rs != null) rs.close();
    if (st != null) st.close();
    //if (conn != null) conn.close(); // depends on wheter you need it again, or whil retrieve a new one
}
于 2012-05-16T11:01:43.123 回答
0

这里的conn是什么?

 Statement stmt = conn.createStatement();

在方法中

public void dbQuery(String query)

如果您希望类的多个方法访问它,则需要将 conn 声明为实例变量。

于 2012-05-16T11:04:34.393 回答
0

你有:

public void dbConnect(String db_connect_string, String username, String password)

和电话:

db.dbConnect(connection, username, password);

您应该将其更改为:

public void dbConnect(Connection conn, String username, String password) {
   ...
   conn = DriverManager.getConnection(db_connect_string, username, password);
   ...
}

和用法:

db.dbConnect(conn, username, password);

您还应该将方法的签名更改为:

public void dbQuery(String query, Connection conn);

以及用于:

db.dbQuery(query, conn);
于 2012-05-16T11:07:41.227 回答