日期:2014-05-18  浏览次数:20722 次

jsp连接Mysql数据库的问题
前台的HTML页面接收用户输入的内容:
<!DOCTYPE   HTML   PUBLIC   "-//W3C//DTD   HTML   4.01   Transitional//EN "   "http://www.w3.org/TR/html4/loose.dtd ">
<html>
<head>
<meta   http-equiv= "Content-Type "   content= "text/html;   charset=gb2312 ">
<title> MySQL   调用实例 </title>
</head>

<body>
    <form   method= "post "   action= "/mysql/servlet/Insert ">
    学生姓名: <input   type= "text "   name= "name "> <br>
    学生年龄: <input   type= "text "   name= "age "> <br>
    学生介绍: <textarea   name= "introduce "   rows= "5 "> </textarea> <br>
    <input   type= "submit "   value= "提交 ">
    <input   type= "reset "   value= "重填 ">
    </form>
</body>
</html>

后台具体的JAVA程序实现代码:
//   Java   Document
/*Insert.java*/
import   java.io.*;
//导入JDBC相关的类
import   java.sql.*;
//导入Mysql的JDBC的相关类
import   org.gjt.mm.mysql.*;
//导入servlet的相关类
import   javax.servlet.*;
import   javax.servlet.http.*;
public   class   Insert   extends   HttpServlet{

//Servlet的dopost方法,来处理用户POST表单的请求
    public   void   doPost(HttpSerletRequest   request,HttpServletResponse   response)
    throws   IOException,ServletException{
     
      //设置输出类型text/html,并且编号GB2312,这样才不会出现中文的乱码
    response.setContentType( "text/html;charset=gb2312 ");
    //定义输出对象
    PrintWriter   out=response.getWriter();
    java.sql.Connection   conn=null;
    java.sql.Statement   st=null;
    //将用户输入转换为8859-1编码的字节,然后再转换成字符,这样就不会出现中文乱码了
    String   name=new   String(request.getparameter( "name ").getBytes( "8859-1 "));
    String   age=new   String(request.getparameter( "age ").getBytes( "8859-1 "));
    String   introduce=new   String(request.getparameter( "introduce ").getBytes( "8859-1 "));  
    try{
    //查找Mysql的JDBC驱动程序,如果找不到会出错
    Class.forName( "org.gjt.mm.mysql.Driver ");
    //连接数据库
    conn=DriverManager.getConnection( "jdbc:mysql://localhost:3306/person ", "root ", "123 ");
    out.println( "与Mysql数据库连接成功! <br> ");
    //生成数据库执行对象
    st=conn.createStatement();
    //执行添加学生的sql语句
    st.executeQuery( "insert   into   student   values( ' "+name+ " ', ' "+age+ " ', ' "+introduce+ " ') ");
    out.println( "学生添加成功! <br> ");
    //关闭数据库
    conn.close();
    out.println( "数据库关闭成功! <br> ");
    &