jsp和mysql连接
2024-09-05 00:19:07
供稿:网友
,欢迎访问网页设计爱好者web开发。中文问题:
jsp和mysql连接的时候,要在每一个jsp文件中加:
<%@ page contenttype="text/html;charset=gb2312" %>
<meta http-equiv="content-type" content="text/html; charset=gb2312">
如果是表单的提交要加上:
jdbc:mysql://127.0.0.1:3306/publish?useunicode=true&characterencoding=gbk" 和
<% request.setcharacterencoding("gbk"); %>
############################################################################
1.
<%@ page contenttype="text/html;charset=gb2312" %>
<meta http-equiv="content-type" content="text/html; charset=gb2312">
<%
java.sql.connection sqlconn;
java.sql.statement sqlstmt;
java.sql.resultset sqlrst;
//regiester jdbc driver
string dbuser="root";
string dbpassword="root";
string dbserver="127.0.0.1"; // can't use localhost , you must use ip or cname
string dbname="publish"; // change to your db name
class.forname("org.gjt.mm.mysql.driver").newinstance();
//connect to the database
sqlconn=java.sql.drivermanager.getconnection
("jdbc:mysql://"+dbserver+":3306/"+dbname+"?useunicode=true&characterencoding=gb2312",
dbuser,dbpassword);
//create the driver handle
sqlstmt=sqlconn.createstatement
(java.sql.resultset.type_scroll_insensitive,java.sql.resultset.concur_read_only);
//excute sql
sqlrst=sqlstmt.executequery("select * from book");
%>
<html>
<head>
<title>jsp-jdbc-mysql testing</title>
</head>
<body>
<table border="1" cellspace ="0" align="center">
<tr><th>id </th>
<th>book name </th></tr>
<% while(sqlrst.next()) {%>
<tr>
<td> <%=sqlrst.getstring("id")%></td>
<td><%=sqlrst.getstring("title")%></td>
</tr>
<%}%>
</table>
</body>
</html>
<%
//sqlrst.close();
sqlstmt.close();
sqlconn.close();
%>
………………………………………………………………………………
2.
<%@ page contenttype="text/html;charset=gb2312" %>
<%
java.sql.connection conn;
java.lang.string strconn;
class.forname("org.gjt.mm.mysql.driver").newinstance();
conn= java.sql.drivermanager.getconnection("jdbc:mysql://127.0.0.1/test","root","");
%>
………………………………………………………………………………
3.
<%@ page import="java.sql.*" %>
<%
out.println(" border is me !");
try {
class.forname("org.gjt.mm.mysql.driver").newinstance();
}
catch (exception e) {
out.println("unable to load driver.");
}
%>
………………………………………………………………………………