所以这是我的问题.. 我正在尝试在国家/地区表中添加国家/地区名称,该表有两个字段:国家/地区 ID 和国家/地区名称。我正在通过用户输入的 jsp 页面获取国家/地区名称,并列出表中可用的所有国家/地区名称,但问题是用户插入的名称不会显示在列表页面中....
这里是代码片段
用于插入记录
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;
}
用于显示记录
public List 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>
<%
}
}
%>
公共(public)静态连接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.
最佳答案
你的显示记录功能看起来非常困惑。可能没有正确发布。 我假设您已经通过提供数据库的名称和密码正确创建了连接。
Class.forName("com.mysql.jdbc.Driver").newInstance();
Connection conn = DriverManager
.getConnection(
"jdbc:mysql://localhost:3306/Twitter?jdbcCompliantTruncation=false&useServerPrepStmts=false&rewriteBatchedStatements=true",
"root", "xxxx");
您的插入查询对我来说看起来是错误的。缺少分号。
String sqlInsert="insert into country(Country_Name) values('"+country+"');";
String sqlselect="select * from country order by country_name;";
发布正在引发的任何异常。
编辑:经OP修正的显示记录功能。我的误解是;是必须的。请参阅this以获得更多说明。
public static Connection createConnection()
{
try
{
Class.forName("com.mysql.jdbc.Driver");
conn=DriverManager.getConnection("jdbc:mysql://localhost:33/ecom_db","root","root");
}
catch(Exception e)
{
e.printStackTrace();
}
return conn;
}
关于java - 最后插入的记录未反射(reflect)在使用 JDBC 的 mysql 中的 select 语句中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15410658/