嗨,我愿意使用jsp形式的bean类在数据库中插入值,我能够做到这一点,但是每当我在表null值中插入值时也出现一点点问题,但我也尝试不了我错了,请解决我的问题

我的bean.java

package com.javabean;


import java.io.*;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;
import java.sql.ResultSet;

public class bean
{

    private String msgid;
    private String message;
    private Connection connection=null;
    private ResultSet rs = null;
    private Statement st = null;
    String connectionURL = "jdbc:mysql://localhost:3306/JspBean";


    public bean()
    {
         try {
             // Load the database driver
            Class.forName("com.mysql.jdbc.Driver");
            // Get a Connection to the database
            connection = DriverManager.getConnection(connectionURL, "root", "");
            }catch(Exception e){
            System.out.println("Exception is ;"+e);
            }

    }
    public void setmsgid(String msgid)
    {
        this.msgid = msgid;
    }

    public String getmsgid()
    {
        return (this.msgid);
    }

    public void setmessage(String message)
    {
        this.message = message;
    }

    public String getmessage()
    {
        return (this.message);
    }

    public void insert()
    {

       try
       {
            String sql = "insert into login(messageid,message) values('"+msgid+"','"+message+"')";
            Statement s = connection.createStatement();
            s.executeUpdate (sql);
            s.close ();
        }catch(Exception e){
            System.out.println("Exception is ;"+e);
        }
    }

}


这是我的jspbean.jsp文件

<%@ page language="Java" import="java.sql.*" %>

<html>
    <head><title>JSP with Javabeans</title></head>
<body bgcolor="#ffccff">
<h1>JSP using JavaBeans example</h1>
    <form name="form1" method="POST">

         ID&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
         <input type="text" name ="msgid"> <br>
         Message<input type="text" name ="message"> <br>
         <br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
         <input type = "submit" value="Submit">
         <jsp:useBean id="sample" class="com.javabean.bean" scope="page">
            <jsp:setProperty name="sample" property="*"/>
        </jsp:useBean>
    </form>
    <% sample.insert();%>
</body>
</html>


我怎样才能做到这一点,请解决我的问题
提前想
Ť

最佳答案

您犯了一些错误:

public void setmsgid(String msgid)
    {
        this.msgid = msgid;
    }
    public String getmsgid()
    {
        return (this.msgid);
    }


您应该更改为:

public String getmsgid()
    {
        return msgid;
    }
public void setmsgid(String msgid)
    {
        this.msgid = msgid;
    }


并添加以下内容:

public String toString()
{
    return "User[msgid="+msgid+",message="+message+"];

}


您必须更改以下一项:

insert into login(username,password) values('"+msgid+"','"+message+"')";




insert into login(username,password) values(?,?)";


更新:

insert into login(messageid,message) values(?,?)";

10-08 07:02