java web開發小記(2)

剛開始接觸web開發感受很難,別人的工程中N多jsp,還有servlet,xml文件。無從下手,其實,web很簡單,簡單到只有一個jsp。html

 1 <%@ page language="java" contentType="text/html; charset=UTF-8"
 2  pageEncoding="UTF-8"%>
 3 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
 4 <html>
 5 <head>
 6 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
 7 <title>Insert title here</title>
 8 </head>
 9 <%@ page import="java.sql.*"%>
10 <body>
11     <%
12  Connection conn = null; 13  try { 14  Class.forName("com.mysql.jdbc.Driver"); // 加載數據庫驅動,註冊到驅動管理器 15             String url = "jdbc:mysql://localhost:3306/test_cal"; // 數據庫鏈接字符串,前幾項是固定的(對於本地服務器),
//最後一項test_cal是數據庫名,要與數據庫對應。
16 String username = "root"; // 數據庫用戶名 17 String password = "123"; // 數據庫密碼, 安裝mysql時本身設置的 18 conn = DriverManager.getConnection(url, username, password); 19 // 建立Connection鏈接 20 // 判斷數據庫鏈接是否爲空 21 if (conn != null) { 22 out.println("數據庫鏈接成功!"); // 輸出鏈接信息 23 conn.close(); // 關閉數據庫鏈接 24 } else { 25 out.println("數據庫鏈接失敗!"); // 輸出鏈接信息 26 } 27 } catch (ClassNotFoundException e) { 28 e.printStackTrace(); 29 } catch (SQLException e) { 30 e.printStackTrace(); 31 } 32 %> 33 </body> 34 </html>

數據庫就連好了(要先建數據庫,這裏是mysql)java

之因此別人的有不少頁,是由於基於功能分離的思想,好比這段代碼,只能用一次,下次再用必須所有重寫,一個項目確定要屢次連接數據庫,所以將它封裝到一個.java文件中·,留一個返回值做爲接口,如:mysql

package com.tuangou.dao; import java.sql.Connection; import java.sql.DriverManager; public class DBConnection { public static Connection getCon(){ Connection conn = null; try{ Class.forName("com.mysql.jdbc.Driver"); // 加載數據庫驅動,註冊到驅動管理器 String url = "jdbc:mysql://localhost:3306/test_cal"; // 數據庫鏈接字符串 String username = "root"; // 數據庫用戶名 String password = "123"; // 數據庫密碼 conn = DriverManager.getConnection(url, username, password); }catch(Exception e){ e.printStackTrace(); } return conn; } }

,這樣,每次要連接數據庫,直接web

     Connection conn = DBConnection.getCon();就能夠省去重寫的麻煩了。sql

此外,新手階段web. xml不須要配置的,知道大體內容就行,你新建一個servlet,eclipse會自動配置。數據庫

數據庫具體增刪查改排推薦參考https://www.cnblogs.com/zilong882008/archive/2011/11/12/2246521.html服務器

爲了防止頁面丟失,這裏轉載一下,如下是轉載內容(如侵權,請聯刪)eclipse

JDBC 筆記1 利用Statement對數據庫進行增刪改查jsp

 

準備工做post

  1新建po類:User

  private int id;                  
private String name;
private String pwd;
        set,get方法省略

   

 2  新建UserDao類,存放增刪改查的相關方法,而且定義連接數據庫的相關性信息(連接地址,用戶名,密碼);

複製代碼
public class UserDao {
private static String jdbcDriver = "com.mysql.jdbc.Driver";
private static String jdbcUrl="jdbc:mysql://localhost:3306/homework";
private static String jdbcuser="root";
private static String jdbcpwd="123";
public boolean ChaRu(User user){ //插入數據
boolean flag=true;

return flag;
}
public boolean XiuGai(User user){ //修改數據
boolean flag=true;

return flag;
}
public boolean ShanChu(int id){ //刪除數據
boolean flag=true;

return flag;
}
public List<User> ChanZhao(){ // 查找數據
List<User> list= new ArrayList<User>();
return list;
}

}
複製代碼

      3 在數據庫中建立表user,表中設置,id    int

                                                      name varchar(20)

                                                      pwd  varchar(20)

1 插入數據

在進行增刪改查操做結束以後,必定要關閉conn,st,rs(僅查找時用到此對象)對象。

複製代碼
public boolean ChaRu(User user){
boolean flag=true;
Connection conn= null;
Statement st=null;
String sql="insert into user(name,pwd) values('"+user.getName()+"','"+user.getPwd()+"')"; //插入數據的SQL語句
try {
Class.forName(jdbcDriver); // 加載驅動器
conn=DriverManager.getConnection(jdbcUrl, jdbcuser, jdbcpwd); // 驅動利用驅動地址,數據庫用戶名,密碼建立鏈接
st=conn.createStatement(); // 鏈接建立數據庫操做對象,Statement是執行數據庫的重要方法
int i=st.executeUpdate(sql); // Statement 對象利用executeUpdate()方法執行sql。
if(i==0){
flag=false; // 後面測試用到flag變量,前面執行sql語句,若是成功i不爲0,true表明執行成功,false表明失敗。
}

} catch (ClassNotFoundException e) { //加載驅動器失敗異常
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SQLException e) { //建立連接失敗異常
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
if(conn!=null){ // 最後關閉鏈接
try {
conn.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if(st!=null){ //關閉Statement
try {
st.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
return flag; // 返回flag
}
複製代碼

 

 

複製代碼
public static void main(String[] args) {
User user=new User(); //初始化 User類 對象user能夠調用set,get方法設置或者得到數據。
UserDao userDao = new UserDao(); //初始化UserDao 類,能夠調用增刪改差的各類方法。
user.setName("lbzz"); // 設置姓名
user.setPwd("123"); // 設置密碼
boolean flag=userDao.ChaRu(user); //執行插入操做,返回值賦給flag
if(flag){ //根據flag判斷執行是否成功。
System.out.println("插入成功");
}else{
System.out.println("插入失敗");
}

}
複製代碼

 

 

2 修改數據

複製代碼
public boolean XiuGai(User user){
boolean flag=true;
Connection conn= null;
Statement st= null;
String sql= "update user set pwd='"+user.getPwd()+"' where name='"+user.getName()+"'";
System.out.println(sql);
try {
Class.forName(jdbcDriver);
conn=DriverManager.getConnection(jdbcUrl, jdbcuser, jdbcpwd);
st=conn.createStatement();
int i=st.executeUpdate(sql);
if(i==0){
flag=false;
}
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
if(conn!=null){
try {
conn.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if(st!=null){
try {
st.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

}
}


return flag;
}
複製代碼

 

測試

複製代碼
public static void main(String[] args) {
User user= new User();
UserDao userDao= new UserDao();
user.setName("lbzz");
user.setPwd("lbzz");
boolean flag=userDao.XiuGai(user);
if(flag){
System.out.println("修改爲功");
}else{
System.out.println("修改失敗");
}
}
複製代碼

 

3 刪除記錄

複製代碼
public boolean ShanChu(int id){
boolean flag=true;
Connection conn= null;
Statement st= null;
String sql="delete from user where id="+id;
try {
Class.forName(jdbcDriver);
conn=DriverManager.getConnection(jdbcUrl, jdbcuser, jdbcpwd);
st=conn.createStatement();
int i=st.executeUpdate(sql);
if(i==0){
flag=false;
}
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
if(conn!=null){
try {
conn.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if(st!=null){
try {
st.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}

return flag;
}
複製代碼

測試

複製代碼
public static void main(String[] args) {
UserDao userDao = new UserDao();
boolean flag= userDao.ShanChu(1);
if(flag){
System.out.println("刪除成功");
}else{
System.out.println("刪除失敗");
}
}
複製代碼

 

4 查找數據

前面增刪改,程序除了sql語句不一樣外,其他相差無幾,查找與前三個程序略有不一樣。

複製代碼
public List<User> ChanZhao(){    //  查詢出來的數據不止一條,因此使用集合
List<User> list= new ArrayList<User>(); // 對集合進行初始化
Connection conn= null;
Statement st=null;
ResultSet rs=null; // ResultSet 返回的是一個結果集
String sql="select * from user";
try {
Class.forName(jdbcDriver);
conn= DriverManager.getConnection(jdbcUrl, jdbcuser, jdbcpwd);
st=conn.createStatement();
rs=st.executeQuery(sql); // 查詢時使用 executeQuery()方法
while(rs.next()){ // 對結果集進行遍歷
User user = new User();
user.setName(rs.getString("name")); // 須要查詢什麼就要像這樣設置什麼
list.add(user); //添加到集合
}

} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
     }finally{
關閉conn,st,rs
    }
return list; //返回list
}
複製代碼

測試

複製代碼
public static void main(String[] args) {
UserDao userDao = new UserDao();
List<User> list=userDao.ChanZhao();
for(User user:list){
System.out.println(user.getName());
}
}
複製代碼
相關文章
相關標籤/搜索