通过构造函数查询数据库

时间:2013-08-27 04:37:46

标签: java sql

我真的从那些善意帮助我解决这个问题的人那里得到了一些帮助。我从昨天起就一直在这里。

看,我正在尝试做的是创建一个数据库查询类,我可以一次又一次地重复使用,而不必每隔一段时间编写一个查询我需要搜索或显示来自数据库。

我希望能够通过构造函数传递查询规范。

然而,我得到了这个错误:

run:
Connecting to a selected database...
Connected database successfully...
Creating statement...
org.h2.jdbc.JdbcSQLException: Data conversion error converting ; SQL statement:

到目前为止,这是我的代码:

import java.sql.*;

public class RsToAList {
    private final String table;
    private final String columns;
    private final String whereColumn;
    private final String equalsEntry;

    public RsToAList (String columns, String table, String whereColumn, String equalsEntry) {
        this.table = table;
        this.columns = columns;
        this.whereColumn = whereColumn;
        this.equalsEntry = equalsEntry;
    }

    // JDBC driver name and database URL
    static String JDBC_DRIVER = "org.h2.Driver";
    static String DB_URL = "jdbc:h2:file:C:/tryDb/tryDb";

    //  Database credentials
    static String USER = "sa";
    static String PASS = "";

    public static void main (String[] args) {
        RsToAList tryAndGet = new RsToAList("fullNames", "CLIENT", "postOfficeBoxNumber", "6448");
        tryAndGet.ourQueryMethod();
    }

    public void ourQueryMethod () {
        Connection conn = null;
        Statement stmt = null;

        try {
            // STEP 2: Register JDBC driver
            Class.forName(getJDBC_DRIVER());

            // STEP 3: Open a connection
            System.out.println("Connecting to a selected database...");
            conn = DriverManager.getConnection(getDB_URL(), getUSER(), getPASS());
            System.out.println("Connected database successfully...");

            // STEP 4: Execute a query
            System.out.println("Creating statement...");
            stmt = conn.createStatement();

            String sql = "SELECT " + (columns) + " FROM " + (table) + " WHERE "+ (whereColumn) +" = "+ (equalsEntry) +"";
            ResultSet rs = stmt.executeQuery(sql);

            //STEP 5: Extract data from result set
            while (rs.next()) {
                // Retrieve by column name
                String first = rs.getString(columns);

                // Display values
                System.out.print("ID: " + first);
            }

            rs.close();
        } catch (SQLException se) {
            // Handle errors for JDBC
            se.printStackTrace();
        } catch (Exception e) {
            // Handle errors for Class.forName
            e.printStackTrace();
        } finally {
            // finally block used to close resources
            try {
                if (stmt != null)
                    conn.close();
            } catch (SQLException se) {
            } // do nothing
            try {
                if (conn != null)
                    conn.close();
            } catch (SQLException se) {
                se.printStackTrace();
            } // end finally try
        } // end try
        System.out.println("Goodbye!");
    } // end main



    /**
     * @return the JDBC_DRIVER
     */
    public static String getJDBC_DRIVER() {
        return JDBC_DRIVER;
    }

    /**
     * @param aJDBC_DRIVER the JDBC_DRIVER to set
     */
    public static void setJDBC_DRIVER(String aJDBC_DRIVER) {
        JDBC_DRIVER = aJDBC_DRIVER;
    }

    /**
     * @return the DB_URL
     */
    public static String getDB_URL() {
        return DB_URL;
    }

    /**
     * @param aDB_URL the DB_URL to set
     */
    public static void setDB_URL(String aDB_URL) {
        DB_URL = aDB_URL;
    }

    /**
     * @return the USER
     */
    public static String getUSER() {
        return USER;
    }

    /**
     * @param aUSER the USER to set
     */
    public static void setUSER(String aUSER) {
        USER = aUSER;
    }

    /**
     * @return the PASS
     */
    public static String getPASS() {
        return PASS;
    }

    /**
     * @param aPASS the PASS to set
     */
    public static void setPASS(String aPASS) {
        PASS = aPASS;
    }

}

我是一个JAVA /编程新手,我正在尝试自学如何在家中进行编码,以防我的问题看起来过于简单,或者我似乎忽略了我的代码中的某些内容。

编辑:

我不确定这是否可以帮助你,但这是创建数据库表的类:

//STEP 1. Import required packages
import java.sql.*;

public class JDBCExampleCreateTables {
    // JDBC driver name and database URL
    private static String JDBC_DRIVER = "org.h2.Driver";
    private static String DB_URL = "jdbc:h2:file:C:/tryDb/tryDb";

    //  Database credentials
    private static String USER = "sa";
    private static String PASS = "";

    public static void main (String[] args) {
        Connection conn = null;
        Statement stmt = null;

        try {
            //STEP 2: Register JDBC driver
            Class.forName(JDBC_DRIVER);

            //STEP 3: Open a connection
            System.out.println("Connecting to a selected database...");
            conn = DriverManager.getConnection(DB_URL, USER, PASS);
            System.out.println("Connected database successfully...");

            //STEP 4: Execute a query
            System.out.println("Creating table in given database...");
            stmt = conn.createStatement();

            String sql = "CREATE TABLE CLIENT " +
                    "(ID INT UNSIGNED NOT NULL AUTO_INCREMENT, " + 
                    " fullNames VARCHAR(255), " + 
                    " iDNumber VARCHAR(255), " + 
                    " pINNumber VARCHAR(255), " + 
                    " passportNumber VARCHAR(255), " + 
                    " postOfficeBoxNumber VARCHAR(255), " + 
                    " postalCode VARCHAR(255), " + 
                    " telephoneNumberLandline VARCHAR(255), " + 
                    " telephoneNumberMobile VARCHAR(255)) "; 

            stmt.executeUpdate(sql);
            System.out.println("Created table in given database...");

        } catch (SQLException se) {
            //Handle errors for JDBC
            se.printStackTrace();
        } catch (Exception e) {
            // Handle errors for Class.forName
            e.printStackTrace();
        } finally {
            // finally block used to close resources
            try {
                if (stmt!=null)
                    conn.close();
            } catch(SQLException se) {
            } // do nothing
            try {
                if (conn!=null)
                    conn.close();
            } catch (SQLException se) {
                se.printStackTrace();
            } // end finally try
        } // end try
        System.out.println("Goodbye!");
    } // end main
} // end

2 个答案:

答案 0 :(得分:4)

在sql语句中看起来像是一个错误。请确保您要比较的数据类型是兼容的.PreparedStatement方便而不是连接查询。

PreparedStatement stm = conn.prepareStatement("select * from person where name=?");
stm.setString(1,"ABC");
ResultSet rs= stm.executeQuery(); 

答案 1 :(得分:1)

虽然您尚未共享where条件的列类型。但最有可能的是,您可能会将字符串值传递给where子句,但不能将其括在单引号中:

String sql = "SELECT " + (columns) + " FROM " + (table) + " WHERE "+ (whereColumn) +" = "+ (equalsEntry) +"";

将其更改为:

String sql = "SELECT " + (columns) + " FROM " + (table) + " WHERE "+ (whereColumn) +" ='"+ (equalsEntry) +"'";

另一个潜在的缺陷候选人是这句话:

String first = rs.getString(columns);

如果您的任何列类型不是VARCHAR

,则可能会出错