使用JSP连接MySql数据库读取HTML表单数据进行存贮
运行环境 tomcat5.5+MySql5.0
编写一个简单的HTML表单:
编写一个简单的HTML表单:
<html>
<head>
</head>
<body>
<form action="http://127.0.0.1/test/login.jsp" method="post">
学号:<input type="text" name="id"><br>
姓名:<input type="text" name="name"><br>
<label>
<input type="radio" name="sex" value="boy" checked>
男</label>
<label>
<input type="radio" name="sex" value="girl">
女</label><br>
电话:<input type="text" name="tel"><br>
<input type="submit" value="提交">
<input type="reset" value="重填">
</form>
</body>
</html>
接这编写一个JSP文件用于读取表单数据<head>
</head>
<body>
<form action="http://127.0.0.1/test/login.jsp" method="post">
学号:<input type="text" name="id"><br>
姓名:<input type="text" name="name"><br>
<label>
<input type="radio" name="sex" value="boy" checked>
男</label>
<label>
<input type="radio" name="sex" value="girl">
女</label><br>
电话:<input type="text" name="tel"><br>
<input type="submit" value="提交">
<input type="reset" value="重填">
</form>
</body>
</html>
Connection conn = null;
Class.forName("com.mysql.jdbc.Driver").newInstance();
conn = java.sql.DriverManager.getConnection("jdbc:mysql://localhost/mydb","root","corsair");
if(conn==null){
System.out.println("get Conn Error");
}
Statement stmt=conn.createStatement();
ResultSet rs=null;
%>
<%
String id,name,sex,tel;
id=request.getParameter("id");
name=request.getParameter("name");
sex=request.getParameter("sex");
tel=request.getParameter("tel");
try{
stmt.executeUpdate("INSERT INTO inf_student(id,name,sex,tel) VALUES ('"+id+"','"+name+"','"+sex+"','"+tel+"')");
}catch(SQLException e){}
stmt.close();
conn.close();
%>
将以上文件保存在tomcat5.5的webapps目录下;然后启动tomcat5.5和mysql数据库,最后打开表单,插入数据提交,并可以mysqlQueryBrower查看到插入数据的情况了。Class.forName("com.mysql.jdbc.Driver").newInstance();
conn = java.sql.DriverManager.getConnection("jdbc:mysql://localhost/mydb","root","corsair");
if(conn==null){
System.out.println("get Conn Error");
}
Statement stmt=conn.createStatement();
ResultSet rs=null;
%>
<%
String id,name,sex,tel;
id=request.getParameter("id");
name=request.getParameter("name");
sex=request.getParameter("sex");
tel=request.getParameter("tel");
try{
stmt.executeUpdate("INSERT INTO inf_student(id,name,sex,tel) VALUES ('"+id+"','"+name+"','"+sex+"','"+tel+"')");
}catch(SQLException e){}
stmt.close();
conn.close();
%>
posted on 2006-09-15 15:42 银河海盗 阅读(1170) 评论(4) 编辑 收藏 所属分类: WEB