1、JSP page连接mysql
对于某一网页edit.jsp,代码设置如下:
<%@ page import = "java.sql.*" %>
<%
Connection con;
Statement sql;
ResultSet rs;
Class.forName("com.mysql.jdbc.Driver").newInstance();
String dbName = "test";
String userName= "root";
String userPasswd = "cxf";
String url="jdbc:mysql://localhost:3306/test";
con = DriverManager.getConnection(url,userName,userPasswd);
if(con == null)
{
out.println("get con error!");
}
sql=con.createStatement();
int d =sql.executeUpdate("update account set password = 'sdfwe' where userName = 'cxf'");
out.print("OK!");
sql.close();
con.close();
%>
2、Jsp servlet连接mysql
servlet连接mysql相对比较复杂,对某一网页index.jsp的如下需求:
<FORM action ="servlet/Sqrt" method = 'get'>
<input type = "text" name = "userName">
<input type = "text" name = "passWord">
<input type = "submit" value = "output" >
</FORM>
处理提交用户名和密码,首先需要建立名字如Sqrt的servlet文件,后缀名为.java,然后在Sqrt.java文件中导入包,添加如下代码:
import javax.servlet.*;
import javax.servlet.http.*;
import java.sql.*;
要想顺利连接mysql,需要在tomcat服务器下配置servlet信息,我用的是tomcat6.0.30,mysql驱动文件拷贝到如下文件夹中:
apache-tomcat-6.0.30/webapps/ROOT/WEB-INF,
并且打开该文件夹中的文件:web.xml 添加如下信息:
<servlet>
<servlet-name>org.apache.jsp.index_jsp</servlet-name>
<servlet-class>org.apache.jsp.index_jsp</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>org.apache.jsp.index_jsp</servlet-name>
<url-pattern>/index.jsp</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>Sqrt</servlet-name>
<servlet-class>Sqrt</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Sqrt</servlet-name>
<url-pattern>/servlet/Sqrt</url-pattern>
</servlet-mapping>
设置完这些之后,我们可以去写Sqrt.java中的代码了:
在servlet中有doGet/dopost操作,实际作用可以是一样的,我们选择在doget中进行演示:
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out
.println("<!DOCTYPE HTML PUBLIC /"-//W3C//DTD HTML 4.01 Transitional//EN/">");
out.println("<HTML>");
out.println(" <HEAD><TITLE>A Servlet</TITLE></HEAD>");
out.println(" <BODY>");
String Name = request.getParameter("userName");//获取数据
String pword = request.getParameter("passWord");
out.println(Name);
out.println(pword);
try
{
Class.forName("com.mysql.jdbc.Driver");
}
catch(ClassNotFoundException e)
{
out.println("shi bai!");
}
String dbName = "test";//数据库名
String userName= "root";//mysql用户名
String userPasswd = "cxf";//密码
String url="jdbc:mysql://localhost:3306/test";
Connection con;
Statement sql;
ResultSet rs;
try{
con = DriverManager.getConnection(url,"root","cxf");
if(con == null)
{
out.println("Get con error!");
}
sql=con.createStatement();
int d =sql.executeUpdate("insert into acc values('"+ Name + "','" + pword +"')");
out.print("OK!");
sql.close();
con.close();
}
catch(SQLException e)
{
out.println("Failure!");
}
out.println(" </BODY>");
out.println("</HTML>");
out.flush();
out.close();
}
如此操作,即可顺利连接mysql!!