jsp连接Mysql数据库
<%@ page contentType="text/html;charset=gb2312"%>
<% @page import="java.sql.*"
import="java.util.*"
import="*"%>
<% Connection conn;
ResultSet rs;
String sql="SELECT * FROM test";
Statement stmt;
try{
Class.forName("org.gjt.mm.mysql.Driver").newInstance();
conn=DriverManager.getConnection("jdbc:mysql://localhost/test");
stmt=conn.createStatement();
rs=stmt.executeQuery(sql);
outTable(rs,out);
}
catch(Exception e){
e.printStackTrace(out);
}
finally{
try{
if(rs!=null)
rs.close();
if(stmt!=null) stmt.close();
if(conn!=null) conn.close();
}
catch(Exception e){}
}
private void outTable(ResultSet rs,PrintWriter out) throw Exception{
out.println("<center><table border='2'>");
ResultSetMetaData rsmd=rs.getMetaData();
int colCount=rsmd.getColumnCount();%>
<tr>
<%for(int i=0;i<colCount;i++){%>
<th><%=rsmd.getColumnLabel(i+1)%><th>
<%}%>
</tr>
<%while(rs.next()){%>
<tr>
<%for(int i=0;i<colCount;i++){
%>
<td><%=rs.getString(i+1)%></td>
<%}%>
</tr>
<%}%>
</table></center>
<%}
%>