JSP程序:谁能发我一个JSP连接数据库的文件,可以用netbeans打开的,急急急!!!!!!
1个回答
展开全部
<%@ page contentType="text/plain; charset=UTF-8"%>
<%@ page language="java"%>
<%@ page import="java.sql.*"%>
<%
out.clear();
String sql = "select * from table"; //定义查询数据库的SQL语句
StringBuffer picInfo = new StringBuffer("[");
int counter = 0;
String drivers = "com.mysql.jdbc.Driver";
String url = "jdbc:mysql://localhost/test?useUnicode=true&characterEncoding=gb2312";//修改成你自己的数据库名称
String user = "root";//用户名
String password = "root";//密码
Connection conn = null;
try {
Class.forName(drivers).newInstance();
conn = DriverManager.getConnection(url, user, password);
} catch (Exception e) {
e.printStackTrace();
}
if (conn == null) {
throw new SQLException(" Cannot get connection.");
}
//声明Connection对象
PreparedStatement pstmt = null; //声明PreparedStatement对象
ResultSet rs = null; //声明ResultSet对象
try {
pstmt = conn.prepareStatement(sql); //根据sql创建PreparedStatement
rs = pstmt.executeQuery(); //执行查询,返回结果集
//遍历结果集,生成JSON格式的查询结果
while (rs.next()) {
if (counter > 0) {
picInfo.append(",");
}
picInfo.append("{");
picInfo.append("'id':'");
picInfo.append(rs.getString("id"));
picInfo.append("','name':'");
picInfo.append(rs.getString("name"));
picInfo.append("','width':'");
picInfo.append("'}");
counter++; //计数器加1
}
} catch (SQLException e) {
System.out.println(e.toString());
} finally {
rs.close(); //关闭结果集
pstmt.close();//关闭PreparedStatement
conn.close();//关闭连接
}
picInfo.append("]");
out.print(picInfo.toString()); //返回查询结果
%>
<%@ page language="java"%>
<%@ page import="java.sql.*"%>
<%
out.clear();
String sql = "select * from table"; //定义查询数据库的SQL语句
StringBuffer picInfo = new StringBuffer("[");
int counter = 0;
String drivers = "com.mysql.jdbc.Driver";
String url = "jdbc:mysql://localhost/test?useUnicode=true&characterEncoding=gb2312";//修改成你自己的数据库名称
String user = "root";//用户名
String password = "root";//密码
Connection conn = null;
try {
Class.forName(drivers).newInstance();
conn = DriverManager.getConnection(url, user, password);
} catch (Exception e) {
e.printStackTrace();
}
if (conn == null) {
throw new SQLException(" Cannot get connection.");
}
//声明Connection对象
PreparedStatement pstmt = null; //声明PreparedStatement对象
ResultSet rs = null; //声明ResultSet对象
try {
pstmt = conn.prepareStatement(sql); //根据sql创建PreparedStatement
rs = pstmt.executeQuery(); //执行查询,返回结果集
//遍历结果集,生成JSON格式的查询结果
while (rs.next()) {
if (counter > 0) {
picInfo.append(",");
}
picInfo.append("{");
picInfo.append("'id':'");
picInfo.append(rs.getString("id"));
picInfo.append("','name':'");
picInfo.append(rs.getString("name"));
picInfo.append("','width':'");
picInfo.append("'}");
counter++; //计数器加1
}
} catch (SQLException e) {
System.out.println(e.toString());
} finally {
rs.close(); //关闭结果集
pstmt.close();//关闭PreparedStatement
conn.close();//关闭连接
}
picInfo.append("]");
out.print(picInfo.toString()); //返回查询结果
%>
更多追问追答
追问
你可以直接给我一个文件吗?里面包括数据库和JSP文件,让我可以直接运行出网页的。谢谢
追答
我把工程和数据库 发给你 给我一个邮箱地址
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询