所以這裏是我的問題.. 我試圖在國家表中添加具有兩個字段的國家/地區ID和國家/地區名稱的國家/地區名稱。我正在通過用戶輸入的jsp頁面輸入一個國家名稱,並列出了表格中所有可用的國家名稱,但是問題在於用戶插入的名稱沒有顯示在列表頁面中......最後一個insterted記錄不反映在使用JDBC的mysql select語句中
這裏是代碼片段
插入記錄
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;
}
顯示記錄
公開名單ListCou n請在()拋出的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。驅動程序「);
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.
我沒有看到交易提交,您的連接是否設置爲自動提交? – Taylor 2013-03-14 15:05:29
請勿使用Java代碼搞亂HTML。請避免這種令人討厭的[scriptlet](http://stackoverflow.com/q/3177733/1037210),它**非常令人沮喪,並且始終使用[PreparedStatements](http://docs.oracle.com/javase/tutorial /jdbc/basics/prepared.html)來緩解SQL注入攻擊。 – Lion 2013-03-14 15:09:06
OP在我的答案評論部分發布了連接聲明。由於連接字符串中沒有參數,因此它被設置爲自動提交模式。 – karmanaut 2013-03-14 15:09:36