各位大大,帮忙啊,救命啊!!!!!!在线等,9999999999999999999999999

zzyy1998 2004-10-13 09:27:53
一个button 在onclick时,能不能调用bean,如果不能,我如何点击之后把数据库中的数据查询出来,我不想把连接数据库的代码放在页面中,能不能做成类,谢谢大家。如果能的话,怎么调用?
...全文
48 4 打赏 收藏 转发到动态 举报
AI 作业
写回复
用AI写文章
4 条回复
切换为时间正序
请发表友善的回复…
发表回复
bhzln 2004-10-13
  • 打赏
  • 举报
回复
用servlet
禽兽v5 2004-10-13
  • 打赏
  • 举报
回复
写错,应该是数据库操作javabean。抱歉。

自行修改openConnection()方法为自己的获得连接代码。
禽兽v5 2004-10-13
  • 打赏
  • 举报
回复
数据库连接池和应用如下:

DbPool.java
----------
import java.sql.*;
import java.util.*;

public class DbPool
{
// 定义为静态变量,将一直存在,直到app关闭。
private static DataSource ds = null;

public static Connection openConnection() throws Exception
{
// 只需要初始化1次
if ( ds == null )
{
Context initContext = new InitialContext();
Context envContext = (Context) initContext.lookup("java:/comp/env");
DataSource ds = (DataSource) envContext.lookup("jdbc/webbalance");
}

return ds.getConnection();
}

public static void closeConnection(Connection conn) throws Exception
{
if ( conn != null )
{
conn.close();
}
}

public static int executeUpdate(String sql) throws Exception
{
int count = 0;

Connection conn = null;
Statement stmt = null;

try
{
conn = openConnection();
stmt = conn.createStatement();

count = stmt.executeUpdate(sql);
}
catch ( Exception e )
{
throw e;
}
finally
{
closeConnection(conn);
}

return count;
}

public static List executeQuery(String sql) throws Exception
{
List list = new ArrayList();

Connection conn = null;
Statement stmt = null;
ResultSet rs = null;

try
{
conn = openConnection();
stmt = conn.createStatement();
rs = stmt.executeQuery(sql);

ResultSetMetaData rsmd = rs.getMetaData();

while ( rs.next() )
{
Map map = new HashMap();

for ( int i = 1; i <= rsmd.getColumnCount(); i++ )
{
map.put(rsmd.getColumnName(i), rs.getString(i));
}

list.add(map);
}

}
catch ( Exception e )
{
e.printStackTrace();
}
finally
{
if ( rs != null ) rs.close();
closeConnection(conn);
}

return list;
}
}
----------
使用:
1.对于insert, update, delete语句,用
int count = CONN.executeUpdate(sql);

2.对于selete语句

// 使用前记得import java.util.*;

List list = CONN.executeQuery(sql);

// 方法一:按名字取值
for ( int i = 0; i < list.size(); i++ )
{
Map map = (HashMap)list.get(i);

out.println((String)mag.get("xx"));
}

// 方法二:遍历取值
for ( int i = 0; i < list.size(); i++ )
{
Map map = (HashMap)list.get(i);

for (Iterator it = map.keySet().iterator(); it.hasNext();)
{
String column_name = (String)it.next();
out.println("column name = " + column_name);
out.println("column value = " + (String)map.get(column_name));
}
}

p.s.
在上面的executeQuery方法中,将ResultSet中的值转储到List对象,因此对性能有影响。
zzyy1998 2004-10-13
  • 打赏
  • 举报
回复
在struts中,我action中查询数据库得到的值怎么传到指定页面上去啊

81,122

社区成员

发帖
与我相关
我的任务
社区描述
Java Web 开发
社区管理员
  • Web 开发社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧