gpt4 book ai didi

java - 如何在jsp中使用bean类向数据库中插入值?

转载 作者:太空宇宙 更新时间:2023-11-04 06:59:59 25 4
gpt4 key购买 nike

嗨,我正在尝试使用 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(?,?)";

关于java - 如何在jsp中使用bean类向数据库中插入值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22225854/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com