从用户查找数据库中的数据

时间:2013-05-08 10:48:18

标签: java database javabeans

我试图让用户查找足球结果,数据库显示数据库的结果,但我不断收到此错误:

Exception in thread "main" java.sql.SQLException: [Microsoft][ODBC Microsoft Access Driver] Too few parameters. Expected 1.

这是我的" useFootballBean.java"豆:

package results;
import results.*;
import java.util.*;
import java.sql.*;
public class UseFootballBean
{
    public static void main(String[] args)
            throws SQLException, ClassNotFoundException
    {
        Scanner keyboard = new Scanner(System.in);
        String home;
        ResultsBean resultsBean = new ResultsBean();

        System.out.print("\nEnter Team: ");
        home = keyboard.next();
        home = resultsBean.getHome(home);
        if (home.equals(null))
            System.out.println(
                    "\n*** No such Team ***");
        else
        System.out.println("\nTeam " + home);
    }

}

这是我的" resultsBean.java"豆

package results;
import java.sql.*;
public class ResultsBean
{
    private Connection connection;
    private Statement statement;
    private ResultSet results;
    public String getHome(String enter)
                throws SQLException, ClassNotFoundException
    {
        String query;
        String team = null;
        connectAndCreateStatement();
        query = "SELECT * FROM Results WHERE homeTeam = "
            + enter;
        results = statement.executeQuery(query);
        if (results.next())
            team = results.getString("homeTeam");
        connection.close();
        return team;
    }

    private void connectAndCreateStatement()
                throws SQLException, ClassNotFoundException
    {
        Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
        connection = DriverManager.getConnection(
                                  "jdbc:odbc:FootballData","","");
        statement = connection.createStatement();
}
}

3 个答案:

答案 0 :(得分:2)

我认为在与字符串值进行比较时,您缺少查询的where子句中所需的单引号。你走了:

where keyword_name='"+keyword_name+"'"

 query = "SELECT * FROM Results WHERE homeTeam = " + '"+ enter + "'";

答案 1 :(得分:1)

您在Sql查询中缺少单引号

query = "SELECT * FROM Results WHERE homeTeam = '"
        + enter+"'";

OR与PreparedStatement接受报价

PreparedStatement stmt = null;
String sql;     
 ResultSet rows=null    

try {
sql = "select * from Results where homeTeam=?" 

stmt = theConn.prepareStatement(sql); 
stmt.setString(1, "Team with ' are permitted!"); 
rows = stmt.executeQuery(); 
stmt.close(); 
 }
 catch (Exception e){ 
 e.printStackTrace(); 
 }
 finally {  if (stmt != null) {
stmt.close();
}

由于

答案 2 :(得分:1)

由于您的查询参数是字符串,因此需要将其括在引号中:

"SELECT * FROM Results WHERE homeTeam = '" + enter + "'";

但是,这仍然是一种糟糕的方法,因为它使您容易受到SQL注入(请记住Bobby Tables?),如果用户输入包含引号字符的团队名称(如England's Greatest Team),则会中断)。因此,您应该使用PreparedStatement(请参阅Java tutorial)。