通过一章的学习,我得到了代码,其中有两个数据库,我已经编译了代码并且它可以工作。我没有尝试调整代码,所以它只有一个数据库,当涉及到选择信息并显示它时,我只是得到一个空白,没有输出,我在哪里出错了,我猜测它在信息选择的某个地方来自数据库?
谢谢
import java.sql.Connection;
import java.sql.Driver;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Enumeration;
public class FootballTeamDataBase
{
Connection connection;
Statement statement;
ResultSet results;
public FootballTeamDataBase()
{
try
{
Class.forName("org.apache.derby.jdbc.ClientDriver");
}
catch (ClassNotFoundException cnfe)
{
System.err.println("Derby driver not found.");
}
try
{
// What drivers are there?
System.out.println("Available drivers:");
Enumeration<Driver> drivers = DriverManager.getDrivers();
while (drivers.hasMoreElements())
{
System.out.println(drivers.nextElement());
}
System.out.println();
connection = DriverManager.getConnection
("jdbc:derby://localhost:1527/MusicShop;create=true;user=admin;pass=admin");
statement = connection.createStatement();
try
{
statement.execute("drop table FootballTeam");
}
catch (SQLException e)
{
System.out.println("Table did not previously exist " + e);
}
// Now create the table.
statement.execute("create table " +
"FOOTBALLTEAM(" +
"ID varchar(12) primary key not null, " +
"POSITION varchar(24), " +
"NAME varchar(24),") ;
}
catch (SQLException sqle)
{
System.err.println("Problem:" + sqle);
}
}
public void addData()
{
try
{
statement.execute("insert into FOOTBALLTEAM values " +
"('1',Keeper','Dale'");
statement.execute("insert into FOOTBALLTEAM values " +
"('2',Defender','Lewis'");
statement.execute("insert into FOOTBALLTEAM values " +
"('3','MIDFIELD','Jones'");
}
catch (SQLException sqle)
{
System.err.println("Problem populating data:" + sqle);
}
}
public void showTeam()
{
try
{
// check the contents of the table
System.out.println("DB contents:");
// select all records
statement.execute("select * from FOOTBALLTEAM");
ResultSet results = statement.getResultSet();
while (results.next())
{
System.out.println(results.getString("ID") + " " + results.getString("POSITION") +
" = " + results.getString("NAME") );
}
}
catch (SQLException e)
{
// nothing wrong
}
}
}
最佳答案
查看这些行,您的 SQL 语句格式错误:
statement.execute("insert into FOOTBALLTEAM values " +
"('1',Keeper','Dale'");
statement.execute("insert into FOOTBALLTEAM values " +
"('2',Defender','Lewis'");
statement.execute("insert into FOOTBALLTEAM values " +
"('3','MIDFIELD','Jones'");
请注意,SQL 语句包含开始 (
但没有结束 )
。像这样更改它:
statement.execute("insert into FOOTBALLTEAM values " +
"('1',Keeper','Dale')");
statement.execute("insert into FOOTBALLTEAM values " +
"('2',Defender','Lewis')");
statement.execute("insert into FOOTBALLTEAM values " +
"('3','MIDFIELD','Jones')");
同样,这看起来不像一个完整的 SQL 语句:
// Now create the table.
statement.execute("create table " +
"FOOTBALLTEAM(" +
"ID varchar(12) primary key not null, " +
"POSITION varchar(24), " +
"NAME varchar(24),") ;
关于Java 数据库帮助,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6480015/