将数据从用户插入数据库

时间:2013-05-11 18:32:50

标签: java database servlets javabeans

我试图允许某人将匹配结果输入到html页面,然后该数据将被输入数据库,但我无法获取任何数据,我缺少什么?

这是我的代码:

EnterResults.html

<html>
<head>
<title>Result</title>
</head>
<body>

<FORM   METHOD=GET ACTION="MatchResult.java">
Enter your home team:
<INPUT  TYPE="text"  NAME="newhomet" VALUE = "" >
Enter your away team:
<INPUT  TYPE="text"  NAME="newawayt" VALUE = "" >
Enter your home score:
<INPUT  TYPE="text"  NAME="newhomes" VALUE = "" >
Enter your away score:
<INPUT  TYPE="text"  NAME="newaways" VALUE = "" >
<INPUT  TYPE="submit"  VALUE = "Submit">
</FORM>
</body>
</html>

MatchResult.jsp

package results;
import java.sql.*;
import java.util.*;
public class MatchResult 
{

private static final String newHomeTeam = null;
private static final String newAwayTeam = null;
private static final String newHomeScore = null;
private static final String newAwayScore = null;
private static Statement statement;
private Connection connection;
public MatchResult() throws ClassNotFoundException, SQLException 
{
    try 
    {
        Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
    } catch (ClassNotFoundException cnfEx)
    {
        throw new ClassNotFoundException("Unable to locate JDBC driver!");
    }

try
{
    connectAndCreateStatement();
    String insertion = "INSERT INTO Results VALUES('"
            + newHomeTeam + "','"
            + newAwayTeam + "','"
            + newHomeScore + "','"
            + newAwayScore + "')";
    statement.executeUpdate(insertion);

    System.out.println("\nContents after insertion:\n");
}
catch(SQLException sqlEx)
{
    System.out.println("* Cannot execute insertion! *");
    sqlEx.printStackTrace();
    System.exit(1);
}
disconnectFromDb();
}



private void connectAndCreateStatement() throws SQLException,
        ClassNotFoundException
        {

    try
    {

        connection = DriverManager.getConnection("jdbc:odbc:FootballData",
                "", "");
    } catch (SQLException sqlEx) 
    {
        throw new SQLException("Unable to connect to database!");
    }

    try
    {
        statement = connection.createStatement();
    } catch (SQLException sqlEx) 
    {
        throw new SQLException("Unable to create SQL statement!");
    }
}

private void disconnectFromDb() throws SQLException
{
    try 
    {
        connection.close();
    } catch (SQLException sqlEx) 
    {
        throw new SQLException("Unable to disconnect from database!");
    }
}
}

2 个答案:

答案 0 :(得分:0)

首先检查web.xml中的URL映射和html代码中的action属性。 其次,您忘记阅读从html页面发送到servlet / jsp的值。 在创建查询之前尝试添加这些行:

newHomeTeam = request.getParameter("newhomet");
newAwayTeam  = request.getParameter("newawayt");
newHomeScore = request.getParameter("newhomes");
newAwayScore = request.getParameter("newaways");

答案 1 :(得分:0)

您是否尝试在表单方法中使用双引号?

<FORM METHOD="GET" ACTION="MatchResult.java">

除此之外,我没有看到任何检索GET传递的参数的代码。您没有将变量分配给GET中的值。 :)