我正在尝试制作一个程序,首先显示数据库中的所有结果,然后让某人输入匹配结果,但是当我尝试插入数据时,我不断收到此错误:
* Cannot execute insertion! *
java.sql.SQLException: [Microsoft][ODBC Microsoft Access Driver] Too few parameters. Expected 1.
at sun.jdbc.odbc.JdbcOdbc.createSQLException(JdbcOdbc.java:6956)
at sun.jdbc.odbc.JdbcOdbc.standardError(JdbcOdbc.java:7113)
at sun.jdbc.odbc.JdbcOdbc.SQLExecDirect(JdbcOdbc.java:3109)
at sun.jdbc.odbc.JdbcOdbcStatement.execute(JdbcOdbcStatement.java:337)
at sun.jdbc.odbc.JdbcOdbcStatement.executeUpdate(JdbcOdbcStatement.java:287)
at results.UserEntryInsertion.main(UserEntryInsertion.java:57)
这是我的插入代码:
package results;
import java.sql.*;
import java.util.*;
public class UserEntryInsertion
{
private static Statement statement;
private static Connection connection;
public static void main(String[] args)
{
Scanner keyboard = new Scanner(System.in);
String newHomeTeam;
String newAwayTeam;
int newHomeScore;
int newAwayScore;
try
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
connection = DriverManager.getConnection(
"jdbc:odbc:FootballData","","");
}
catch(ClassNotFoundException cnfEx)
{
System.out.println("* Unable to load driver! *");
System.exit(1);
}
catch(SQLException sqlEx)
{
System.out.println(
"* Cannot connect to database! *");
System.exit(1);
}
System.out.println("\nInitial table contents:\n");
displayTableContents();
System.out.print("\nPress <Enter> to continue...");
keyboard.nextLine();
System.out.print("\nNew Home Team ");
newHomeTeam = keyboard.next();
System.out.print("\nNew Away Team ");
newAwayTeam = keyboard.next();
System.out.print("\nNew Home Score ");
newHomeScore = keyboard.nextInt();
System.out.print("\nNew Away Score ");
newAwayScore = keyboard.nextInt();
try
{
String insertion = "INSERT INTO Results VALUES("
+ newHomeTeam + ",'"
+ newAwayTeam + "','"
+ newHomeScore + "',"
+ newAwayScore + ")";
statement.executeUpdate(insertion);
System.out.println("\nContents after insertion:\n");
displayTableContents();
}
catch(SQLException sqlEx)
{
System.out.println("* Cannot execute insertion! *");
sqlEx.printStackTrace();
System.exit(1);
}
closeDown();
}
static void displayTableContents ()
{
ResultSet results = null;
try
{
statement = connection.createStatement();
results = statement.executeQuery(
"SELECT * FROM Results");
while (results.next())
{
System.out.println("Home Team"+ results.getString(1));
System.out.println("Away Team:"+ results.getString(2));
System.out.println("Home Score:"+ results.getInt(3));
System.out.println("Away Score:" + results.getInt(4));
System.out.println();
}
}
catch(SQLException sqlEx)
{
System.out.println("* Error retrieving data! *");
sqlEx.printStackTrace();
System.exit(1);
}
}
static void closeDown()
{
try
{
connection.close();
}
catch(SQLException sqlEx)
{
System.out.println("* Unable to disconnect! *");
sqlEx.printStackTrace();
}
}
}