Jsp连接mysql

来自个人维基
2015年5月6日 (三) 20:35Hovercool讨论 | 贡献的版本

(差异) ←上一版本 | 最后版本 (差异) | 下一版本→ (差异)
跳转至: 导航搜索

测试代码:

<%@ page contentType="text/html;charset=Gb2312"%> <%--UTF-8--%>
<%@ page import="java.sql.*"%>
<%
String dbName = "temp";
String tbName = "mytest";
String dbUsr = "root";
String dbPwd = "123456";

Class.forName("com.mysql.jdbc.Driver");
Connection con=DriverManager.getConnection("jdbc:mysql://localhost/"+dbName,dbUsr,dbPwd);
Statement stmt=con.createStatement();
String cmd = new String("select * from ");
cmd = cmd.concat(tbName);
ResultSet rs=stmt.executeQuery(cmd);
while(rs.next())
{
%>
<%=rs.getString("uid")%>
<%=rs.getString("uname")%><br>
<%
}
rs.close();
stmt.close();
con.close();
%>
<%out.print("数据库操作成功,恭喜你");%>

提示出错:

org.apache.jasper.JasperException: Unable to compile class for JSP: 

An error occurred at line: 26 in the jsp file: /testjdbc.jsp
String literal is not properly closed by a double-quote
23: stmt.close();
24: con.close();
25: %>
26: <%out.print("数据库操作成功,恭喜你");%>
27: 

原因分析:

linux默认不支持Gb2312编码,改为UTF-8后则一切ok.