【发布时间】:2013-03-14 13:29:13
【问题描述】:
所以这是我的问题.. 我正在尝试在具有两个字段国家 ID 和国家名称的国家表中添加国家名称。我通过用户输入的 jsp 页面获取国家名称,并列出表中所有可用的国家名称,但问题是用户插入的名称不会显示在列表页面中......
这里是代码 sn-ps
用于插入记录
public boolean insertCountry(CountryBean bean)
{
String country=bean.getCountryname();
boolean flag=false;
int result;
try
{
conn=connection.createConnection();
stmt=conn.createStatement();
String sqlInsert="insert into country(Country_Name) values('"+country+"')";
result=stmt.executeUpdate(sqlInsert);
if(result>0)
flag=true;
else
flag=false;
}
catch(Exception e)
{
e.printStackTrace();
}
return flag;
}
用于显示记录
公共列表 ListCountry() 抛出 SQLException {
List<CountryBean> list=new ArrayList<CountryBean>();
CountryBean bean;
Connection conn=null;
Statement stmt=null;
ResultSet rs=null;
try
{
conn=connection.createConnection();
stmt=conn.createStatement();
String sqlselect="select * from country order by country_name";
rs=stmt.executeQuery(sqlselect);
if(rs!=null)
{
while(rs.next())
{
bean=new CountryBean();
bean.setCountryname(rs.getString("country_name"));
System.out.println(rs.getString("country_name"));
list.add(bean);
}
}
}
catch(Exception e)
{
e.printStackTrace();
}
finally
{
if(rs!=null){
rs.close();
}
if(conn!=null){
conn.close();
}
if(stmt!=null){
stmt.close();
}
}
return list;
}
}
listing jsp page
<table border="2">
<tr>
<th>Country Name</th>
</tr>
<%
for (int i = 0; i < list.size(); i++) {
CountryBean bean = list.get(i);
%>
<tr>
<td><%=bean.getCountryname()%></td>
<%
}
}
%>
公共静态连接 createConnection() { 尝试 { Class.forName("com.mysql.jdbc.Driver");
conn=DriverManager.getConnection("jdbc:mysql://localhost:3309/ecom_db","root","root");
}
catch(Exception e)
{
e.printStackTrace();
}
return conn;
} Name of the country is successfully entered in to the database nothing wrong with the queries but the problem is it does not appear in to the list in table tag.list.size method returns only previously inserted countries not the new one.
【问题讨论】:
-
我没有看到事务提交,您的连接是否设置为自动提交?
-
不要将 HTML 与 Java 代码混淆。请避免使用这种可恶的scriptlet,这是高度不鼓励的,并始终使用PreparedStatements 来缓解SQL 注入攻击。
-
OP 在我的答案评论部分发布了连接声明。由于连接字符串中没有参数,所以设置为自动提交模式。
标签: java mysql jsp jakarta-ee jdbc