用jsp向数据库插入数据

Lianjie.java是连接数据库的,input.jsp是表单输入数据,然后通过add.jsp向数据库添加数据。但是添加不上代码如下Lianjie.java如下:package com.example;import java.sql.*;public class Lianjie { private static final String URL="jdbc:mysql://localhost:3306/student"; private static final String USER="root"; private static final String PASSWORD=""; protected static Statement s=null; protected static ResultSet rs=null; protected static Connection conn=null; public static synchronized Connection getConnection(){ try{ Class.forName("com.mysql.jdbc.Driver"); conn=DriverManager.getConnection(URL,USER,PASSWORD); }catch (Exception e) { e.printStackTrace(); } return conn; } public static int executeUpdate(String sql){ int result=0; try { s=getConnection().createStatement(); result=s.executeUpdate(sql); } catch (Exception e) { e.printStackTrace(); } return result; } public static ResultSet executeQuery(String sql){ try { s=getConnection().createStatement(); rs=s.executeQuery(sql); } catch (Exception e) { e.printStackTrace(); } return rs; } public static PreparedStatement executePreparedStatement(String sql){ PreparedStatement ps=null; try { ps=getConnection().prepareStatement(sql); } catch (Exception e) { e.printStackTrace(); } return ps; } public static void close(){ try{ if(rs!=null) rs.close(); if(s!=null) s.close(); if(conn!=null) conn.close(); }catch (Exception e) { e.printStackTrace(); } }}input.jsp和add.jsp如下

第1个回答  2018-04-10
你的问题我知道了,你想往数据库里插入数据,单纯从jsp页面插入没有现实意义,可以考虑到再编写一个表单页面提交表单数据,在jsp页面用统配符向数据库插入数据。
我大致一个小例子你看看。
zhuce.html

<html>
<body>
<form name="form1" method="post" action="register.jsp">
<p align="center">用户名:
<input type="text" name="name">
</p>
<p align="center">密码:
<input type="password" name="password">
</p>
<p align="center">
<input type="submit" name="Submit" value=" 注 册">
</p>
</form>
</body>
</html>
register.jsp
<%@ page contentType="text/html; charset=gb2312" language="java" import="java.sql.*" errorPage="" %>
<html>
<body>
<%
request.setCharacterEncoding("GBK");
String name=request.getParameter("name");//内置对象应该会吧
String password=request.getParameter("password");
try{
Class.forName("org.gjt.mm.mysql.Driver"); //驱动程序你自己的,我的是com.mysql.jdbc.Driver
String url="jdbc:mysql://localhost:3306/tian";//你自己设置数据库名称
Connection con=DriverManager.getConnection(url,"root",""); //如果你mysql中root的密码是空的话最好写成""代替null
String sql="insert into txt (name,password) values ('"+name+"','"+password+"')";//你使用的表是txt,sql建表自己看着办吧
Statement stmt=con.createStatement();
if{
stmt.executeUpdate(sql);
response.sendRedirect("success.html");//根据结果定向成功页面
}else{
response.sendRedirect("f.html");//失败页面
}
}catch(Exception e){
e.printStackTrace();
System.out.println(e);
}
%>
</body>
</html>
至于success.jsp和f.jsp比较简单自己写下吧。

不会了可以上网查资料,或许再提问吧本回答被网友采纳
相似回答