本文目錄一覽:
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向資料庫插入多條數據,在線等,急
假設我們向mysql資料庫中的news資料庫中的users表中插入roleID、username、password三項數值,資料庫地址為本地,賬號密碼都是root。
首先第一步:
我們需要建立資料庫,在資料庫中建立users表,欄位分別為id(主鍵) username(賬號) password(密碼) roleID(角色),這個不做詳細解釋。
接下來我們需要建立jsp頁面,在這裡建立3個jsp頁面,分別為index.jsp(插入數據頁面)、fuction.jsp(執行插入數據的邏輯操作)、success.jsp(跳轉成功頁面)。PS:其實還可以建立一個插入失敗時跳轉的頁面,自己可以試試。
用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比較簡單自己寫下吧。
不會了可以上網查資料,或許再提問吧
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-tw/n/200521.html