1

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

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

这是我的“useFootballBean.java”bean:

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”bean

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();
}
}
4

3 回答 3

2

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

where keyword_name='"+keyword_name+"'"

 query = "SELECT * FROM Results WHERE homeTeam = " + '"+ enter + "'";
于 2013-05-08T10:55:22.573 回答
1

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

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

然而,这仍然是一个糟糕的方法,因为它使您容易受到 SQL 注入的攻击(还记得Bobby Tables吗?),并且如果用户输入包含引号字符的团队名称(如England's Greatest Team),则会中断。因此,您应该使用PreparedStatement(参见Java 教程)。

于 2013-05-08T11:11:08.793 回答
1

您在 Sql 查询中缺少单引号

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

或使用 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();
}

谢谢

于 2013-05-08T10:58:53.373 回答