很多事情,在我們沒有做之前我們覺得好難,但是只要你靜下心來,畢竟這些都是人搞出來的,只要你是人,那就一定可以明白。
配置:JDK1.8,MySQL5.7,eclipse:Neon Release (4.6.0),connector:mysql-connector-java-3.1.6-bin.jar
1、java連接數據庫,並將結果顯示在jsp頁面中
這里需要用到tomcat服務器,怎么配置可以百度,下面會給出項目的工程配置和源代碼以及實際運行效果。
這里,需要注意的一點是關於mysql-connector-java-3.1.6-bin.jar(版本隨意,不要太舊就行)的配置,由於我新建的是“WEB->Dynamic Web project”,所以我們需要把mysql-connector-java-3.1.6-bin.jar放在WebContent->WEB-INF->lib文件夾下。不然會出現下圖所示的錯誤。
由於是Dynamic Web project,所以不能采用Build Path->Configure Build Path->Add External JARs的形式添加mysql-connector-java-3.1.6-bin.jar,如果你執意要如此,還是會出現上圖所示的找不到合適驅動的錯誤。
下面給出正確的工程拓撲結構及源碼:
web.xml源碼:
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0"> <display-name>JDBCTest1</display-name> <welcome-file-list> <welcome-file>index.html</welcome-file> <welcome-file>index.htm</welcome-file> <welcome-file>index.jsp</welcome-file> <welcome-file>default.html</welcome-file> <welcome-file>default.htm</welcome-file> <welcome-file>default.jsp</welcome-file> </welcome-file-list> </web-app>
index.jsp源碼:
<%@ page language="java" import="java.sql.*" pageEncoding="UTF-8"%> <% try { Class.forName("com.mysql.jdbc.Driver"); } catch (ClassNotFoundException e) { System.out.println("加載數據庫驅動時拋出異常,內容如下:"); e.printStackTrace(); } Connection conn = DriverManager .getConnection( "jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf8","root", "w513723"); Statement stmt = conn.createStatement(); ResultSet rs = stmt .executeQuery("select * from user"); while (rs.next()) { out.println("ID:"+rs.getString(1)+" "+"用戶名:" + rs.getString(2)+" " + " 密碼:" + rs.getString(3)+".mdb<br/>"); } rs.close(); stmt.close(); conn.close(); %> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Insert title here</title> </head> <body> </body> </html>
user表結構:
實際運行效果:
2、java連接數據庫,封裝創建、插入、查找接口
這個沒有太多講的,這里與上面的區別在於這是普通的java工程,不是動態web項目,所以mysql-connector-java-3.1.6-bin.jar使用Build Path->Configure Build Path->Add External JARs添加即可。
(代碼源於《JAVA web程序設計 慕課版》明日科技)有時間我會增減刪除和更新表的操作。
工程拓撲結構:
源代碼:
JDBCUtil.java
import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.Statement; public class JDBCUtil { /*使用靜態代碼塊完成驅動的加載*/ static { try { String driverName = "com.mysql.jdbc.Driver"; Class.forName(driverName); } catch (Exception e) { e.printStackTrace(); } } /*提供連接的方法*/ public static Connection getConnection() { Connection con = null; try { //連接指定的MMySQL數據庫,三個參數分別是:數據庫地址、賬號、密碼 con = DriverManager.getConnection("jdbc:mysql://127.0.0.1/test?useUnicode=true&characterEncoding=utf8", "root", "w513723"); } catch (Exception e) { e.printStackTrace(); } return con; } /*關閉連接的方法*/ public static void close(ResultSet rs, Statement stmt, Connection con) { try { if (rs != null) rs.close(); } catch (Exception ex) { ex.printStackTrace(); } try { if (stmt != null) stmt.close(); } catch (Exception ex) { ex.printStackTrace(); } try { if (con != null) con.close(); } catch (Exception ex) { ex.printStackTrace(); } } }
DaoTest.java
import java.sql.Connection; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; public class DaoTest { Connection con; Statement stmt; ResultSet rs; public Connection getCon() { return con; } public Statement getStmt() { return stmt; } public ResultSet getRs() { return rs; } public DaoTest(Connection con) { this.con = con; try { stmt = con.createStatement(); } catch (SQLException e) { e.printStackTrace(); } } public void createTable() throws SQLException { stmt.executeUpdate("DROP TABLE IF EXISTS `jdbc_test` ");//刪除相同名稱的表 String sql = "create table jdbc_test(id int,name varchar(100)) "; stmt.executeUpdate(sql);//執行SQL System.out.println("jdbc_test表創建完畢"); } public void insert() throws SQLException { String sql1 = "insert into jdbc_test values(1,'tom') "; String sql2 = "insert into jdbc_test values(2,'張三') "; String sql3 = "insert into jdbc_test values(3,'999') "; stmt.addBatch(sql1); stmt.addBatch(sql2); stmt.addBatch(sql3); int[] results = stmt.executeBatch();//批量運行sql for (int i = 0; i < results.length; i++) { System.out.println("第" + (i + 1) + "次插入返回" + results[0] + "條結果"); } } public void select() throws SQLException { String sql = "select id,name from jdbc_test "; rs = stmt.executeQuery(sql); System.out.println("---數據庫查詢的結果----"); System.out.println("id\tname"); System.out.println("---------------------"); while (rs.next()) { String id = rs.getString("id"); String name = rs.getString("name"); System.out.print(id + "\t" + name+"\n"); } } public static void main(String[] args) { Connection con = JDBCUtil.getConnection(); DaoTest dao = new DaoTest(con); try { dao.createTable(); dao.insert(); dao.select(); } catch (SQLException e) { e.printStackTrace(); } finally { JDBCUtil.close(dao.getRs(), dao.getStmt(), dao.getCon()); } } }
程序運行控制台輸出:
數據庫查詢結構:
增加刪除和更新操作(其實很簡單的,當初為什么沒有寫呢?被嚇到了???)
import java.sql.Connection; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; public class DaoTest { Connection con; Statement stmt; ResultSet rs; public Connection getCon() { return con; } public Statement getStmt() { return stmt; } public ResultSet getRs() { return rs; } public DaoTest(Connection con) { this.con = con; try { stmt = con.createStatement(); } catch (SQLException e) { e.printStackTrace(); } } public void createTable() throws SQLException { stmt.executeUpdate("DROP TABLE IF EXISTS `jdbc_test` ");//刪除相同名稱的表 String sql = "create table jdbc_test(id int,name varchar(100)) "; stmt.executeUpdate(sql);//執行SQL System.out.println("jdbc_test表創建完畢"); } public void insert() throws SQLException { String sql1 = "insert into jdbc_test values(1,'tom') "; String sql2 = "insert into jdbc_test values(2,'張三') "; String sql3 = "insert into jdbc_test values(3,'999') "; stmt.addBatch(sql1); stmt.addBatch(sql2); stmt.addBatch(sql3); int[] results = stmt.executeBatch();//批量運行sql for (int i = 0; i < results.length; i++) { System.out.println("第" + (i + 1) + "次插入返回" + results[0] + "條結果"); } } public void select() throws SQLException { String sql = "select id,name from jdbc_test "; rs = stmt.executeQuery(sql); System.out.println("---數據庫查詢的結果----"); System.out.println("id\tname"); System.out.println("---------------------"); while (rs.next()) { String id = rs.getString("id"); String name = rs.getString("name"); System.out.print(id + "\t" + name+"\n"); } } public void delete() throws SQLException { String sql="delete from jdbc_test where id in (1,2)"; int tmp=stmt.executeUpdate(sql); //這里函數的返回值表示成功刪除了多少條數據 if (tmp<1) { System.out.println("要刪除的數據不存在或刪除錯誤!"); } else { System.out.println("成功刪除"+tmp+"條數據"); } } public void update() throws SQLException { String sql="update jdbc_test set name='shuai' where id=3"; int tmp=stmt.executeUpdate(sql); //這里函數的返回值表示成功更新了多少條數據 if (tmp<1) { System.out.println("需要更新的數據不存在或更新錯誤!"); } else { System.out.println("成功更新"+tmp+"條數據"); } } public static void main(String[] args) { Connection con = JDBCUtil.getConnection(); DaoTest dao = new DaoTest(con); try { dao.createTable(); dao.insert(); dao.select(); dao.delete(); dao.select(); dao.update(); dao.select(); } catch (SQLException e) { e.printStackTrace(); } finally { JDBCUtil.close(dao.getRs(), dao.getStmt(), dao.getCon()); } } }
運行截圖: