本文目錄一覽:
用JSP通過表單向資料庫添加內容
你這應該是用的是struts2吧,首先
form id=”form1″ name=”form1″ method=”post” action=””
form表單里的action應該填值為addMessage.action,然後再在struts2裡面配置這個action,具體的為:
action name=”addMessage.action”
class=”test.add” method=”addMessage”
result name=”success”test.jsp/result
/action
這樣改完以後再看看
JSP中如何對資料庫中的數據進行刪除增加等操作
問題太抽象,/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/package ******;
import java.io.PrintWriter;
import java.sql.*;/**
* @author wfg
*/
public class DB_Conn {
private String driverName = “com.mysql.jdbc.Driver”; //JDBC驅動
private String userName = “root”; //資料庫用戶名
private String userPwd = “*****”; //資料庫用戶密碼
private String dbName = “******”; //資料庫名
private String url = “jdbc:mysql://localhost:3306/”+dbName+”?user=”+userName+
“password=”+userPwd; //資料庫連接字元串
private Connection conn = null; //資料庫連接對象
public Statement sm = null; //資料庫語句對象
private PrintWriter out = null; //建立資料庫連接函數
public void ConnectDB(){
try{
Class.forName(driverName).newInstance();
conn = DriverManager.getConnection(url);
sm = conn.createStatement();
}
catch(Exception e){
e.printStackTrace();
out.print(“資料庫連接失敗!”);
}
} //釋放資料庫連接函數
public void CloseDB(){
try{
if(sm != null){
sm.close();
}
conn.close();
}
catch(SQLException SqlE){
SqlE.printStackTrace();
out.print(“資料庫關閉失敗!”);
}
}
}
這是先建立連接
用jsp向資料庫插入數據
你的問題我知道了,你想往資料庫里插入數據,單純從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比較簡單自己寫下吧。
不會了可以上網查資料,或許再提問吧
原創文章,作者:SNAUJ,如若轉載,請註明出處:https://www.506064.com/zh-tw/n/331484.html