系列文章目錄
IDEA上面書寫wordcount的Scala文件具體操作
IDEA創(chuàng)建項(xiàng)目的操作步驟以及在虛擬機(jī)里面創(chuàng)建Scala的項(xiàng)目簡(jiǎn)單介紹
目錄
系列文章目錄
前言
一 準(zhǔn)備工作
1.1 安裝Maven
1.1.1?Maven安裝配置步驟
1.1.2?解壓相關(guān)的軟件包
1.1.3?Maven 配置環(huán)境變量
1.1.4 配置Maven的私服
1.2 創(chuàng)建一個(gè)本地的MySQL數(shù)據(jù)庫(kù)和數(shù)據(jù)表
二 創(chuàng)建Java項(xiàng)目
2.1 方式一 數(shù)據(jù)庫(kù)連接池druid
2.1.1 MySQL-connector-java資源分享鏈接
2.1.2 druid資源鏈接
2.2?創(chuàng)建Java項(xiàng)目步驟如下
2.2.1 創(chuàng)建項(xiàng)目目錄
2.2.2??創(chuàng)建一個(gè)新的Java類
2.2.3 導(dǎo)入jar包?
?2.2.4 將jar包加載到library
?2.2.5 編寫Java代碼
版本一?
版本二
2.3 方式二 配置文件的形式加載
2.3.1 在src目錄之下創(chuàng)建配置文件
2.3.2 在配置文件當(dāng)中添加如下的信息
2.3.3 創(chuàng)建一個(gè)demo2的Java文件
?2.3.4 編輯Java代碼
三 在IDEA上創(chuàng)建Maven項(xiàng)目來實(shí)現(xiàn)上述的功能
3.1?創(chuàng)建項(xiàng)目
?3.2 創(chuàng)建一個(gè)Java類
?3.3 編輯Java代碼和配置文件
3.4 Java代碼模塊講解
3.4.1 Java Scanner 類
3.4.2 系統(tǒng)添加數(shù)據(jù)模塊方法
3.4.3? 編輯MySQL與druid依賴
3.4.4 編輯插入數(shù)據(jù)方法
3.4.5 編輯查詢代碼
3.4.6? 完整的優(yōu)化后的代碼
思考——如何優(yōu)化上述的Java代碼??
總結(jié)
前言
本文主要介紹IDEA項(xiàng)目實(shí)踐,創(chuàng)建Java項(xiàng)目以及創(chuàng)建Maven項(xiàng)目案例、使用數(shù)據(jù)庫(kù)連接池創(chuàng)建項(xiàng)目簡(jiǎn)介
一 準(zhǔn)備工作
1.1 安裝Maven
Maven資源分享包
鏈接:https://pan.baidu.com/s/1D3SHLKTMTTUDYLv45EXgeg?pwd=kmdf?
提取碼:kmdf
1.1.1?Maven安裝配置步驟
1. 解壓 apache-maven-3.6.1.rar 既安裝完成2. 配置環(huán)境變量 MAVEN_HOME 為安裝 路徑,在 Path 添加 %MAVEN_HOME%/bin 目錄3. 配置本地倉(cāng)庫(kù):修改 conf /settings.xml 中的 < localRepository > 為一個(gè)指定目錄4. 配置阿里云私服:修改 conf /settings.xml 中的 <mirrors> 標(biāo)簽,為其添加如下子標(biāo)簽
1.1.2?解壓相關(guān)的軟件包
解壓你的Maven包,放在你的文件夾里面,配置相關(guān)的本地倉(cāng)庫(kù)文件
1.1.3?Maven 配置環(huán)境變量
?打開Windows1的高級(jí)設(shè)置,配置相關(guān)的環(huán)境變量
第一處
MAVEN_HOME
D:\apache-maven-3.9.3
第二處?
?Path
%MAVEN_HOME%/bin
1.1.4 配置Maven的私服
?需要添加的內(nèi)容如下:
<mirror>
<id>alimaven</id>
<name>aliyun maven</name>
<url>http://maven.aliyun.com/nexus/content/groups/public/</url>
<mirrorOf>central</mirrorOf>
</mirror>
先創(chuàng)建一個(gè)本地倉(cāng)庫(kù)文件夾【myRepository】你的倉(cāng)庫(kù)創(chuàng)建在你安裝了Maven的地方。
在notepad++查找本地的【localRepository】
沒有notepad++也可以使用記事本編輯,只要將內(nèi)容修改完,并且保存完成即可。
?在setting文件夾里面加入本地倉(cāng)庫(kù)位置
<localRepository>D:\apache-maven-3.9.3\myRepository</localRepository>
?查找mirrors位置,修改為阿里的私服。
?添加完成之后記得保存~
編輯完成之后退出。本地倉(cāng)庫(kù)就配置完成了。
1.2 創(chuàng)建一個(gè)本地的MySQL數(shù)據(jù)庫(kù)和數(shù)據(jù)表
在此之前,需要配置本地MySQL服務(wù)的連接如下:
?MySQL以及MySQL workbench的安裝與配置【超詳細(xì)安裝教程】
創(chuàng)建數(shù)據(jù)庫(kù)和數(shù)據(jù)表的SQL語(yǔ)句?
// 創(chuàng)建名為 test 的數(shù)據(jù)庫(kù)
CREATE DATABASE test;
// 使用 test 數(shù)據(jù)庫(kù)
USE test;
// 創(chuàng)建名為 websites 的表
CREATE TABLE `websites` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` char(20) NOT NULL DEFAULT '' COMMENT '站點(diǎn)名稱',
`url` varchar(255) NOT NULL DEFAULT '',
`alexa` int(11) NOT NULL DEFAULT '0' COMMENT 'Alexa 排名',
`country` char(10) NOT NULL DEFAULT '' COMMENT '國(guó)家',
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=10 DEFAULT CHARSET=utf8;
// 在 websites 中插入數(shù)據(jù)
INSERT INTO `websites` VALUES ('1', 'Google', 'https://www.google.cm/', '2', 'USA'),
('2', '淘寶', 'https://www.taobao.com/', '13', 'CN'),
('3', '菜鳥教程', 'http://www.runoob.com', '5892', 'CN'),
('4', '微博', 'http://weibo.com/', '20', 'CN'),
('5', 'Facebook', 'https://www.facebook.com/', '3', 'USA'),
('6', 'JueJin', 'https://www.juejin.cn/', '2213', 'CN');
創(chuàng)建之后的數(shù)據(jù)庫(kù)如下圖所示的界面:?
二 創(chuàng)建Java項(xiàng)目
2.1 方式一 數(shù)據(jù)庫(kù)連接池druid
創(chuàng)建步驟如下:
1. 導(dǎo)入jar包(mysql-connection-java.jar,druid.jar),同時(shí)加入到類加載路徑中
2. 直接創(chuàng)建連接池對(duì)象:new對(duì)象 DruidDataSource
3. 然后設(shè)置屬性。
? ?1. setDriverClassName()
? ?2. setUrl()
? ?3. setUsername()
? ?4. setPassword()
? ?5. setInitialSize() ?//初始連接數(shù)
? ?6. setMaxSize() ? //最大連接數(shù)
? ?7. setMaxWait() ? //最大等待時(shí)間
4. 通過連接池對(duì)象,獲取數(shù)據(jù)庫(kù)連接
方式一的缺點(diǎn):將MySQL的URL和用戶以及密碼是寫死的,當(dāng)你要修改的時(shí)候不好修改
2.1.1 MySQL-connector-java資源分享鏈接
MySQL-connector-java-8.0.31版本百度網(wǎng)盤連接
鏈接:https://pan.baidu.com/s/1A2NtVswiJjvxFB68GZ77Vw?pwd=wcmo?
提取碼:wcmo
MySQL-connector-java-5.1.49版本百度網(wǎng)盤連接
鏈接:https://pan.baidu.com/s/1FPL23h6Ca7_Y0N_HYZSm0Q?pwd=6kwi?
提取碼:6kwi
2.1.2 druid資源鏈接
druid-1.1.12版本
鏈接:https://pan.baidu.com/s/13Bwl-R3gN0fU5qHAGFHzwA?pwd=gu9g?
提取碼:gu9g
2.2?創(chuàng)建Java項(xiàng)目步驟如下
2.2.1 創(chuàng)建項(xiàng)目目錄
選擇創(chuàng)建Java文件
?繼續(xù)下一步
?創(chuàng)建你的問價(jià)存儲(chǔ)位置,此處建議專門寫一個(gè)存放IDEA項(xiàng)目的文件夾。
2.2.2??創(chuàng)建一個(gè)新的Java類
在src文件里面創(chuàng)建一個(gè)新的Java類
名字為: com.ambow.druid.DruidDemo
解釋——前三個(gè)為包名稱,后面為類名稱。
2.2.3 導(dǎo)入jar包?
在項(xiàng)目里面新建一個(gè)文件夾導(dǎo)入前面的兩個(gè)jar包【MySQL-connector-java-8.0.31和druid-1.1.12
】,需要自己創(chuàng)建一個(gè)libs文件夾存放這兩個(gè)jar包。
?此處記得選擇自己的MySQL對(duì)應(yīng)的Java包,下載之后,將兩個(gè)jar包復(fù)制,將其粘貼在libs文件夾里面即可。
?此處點(diǎn)擊ok即可。
同上
?2.2.4 將jar包加載到library
在兩個(gè)jar包上面,鼠標(biāo)右鍵,選擇as a library加載
?點(diǎn)擊OK即可
?2.2.5 編寫Java代碼
版本一?
package com.ambow.druid;
import java.sql.*;
//方式一: druid的數(shù)據(jù)庫(kù)連接池
public class DruidDemo {
// MySQL 8.0 以下版本 - JDBC 驅(qū)動(dòng)名及數(shù)據(jù)庫(kù) URL
// static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
// static final String DB_URL = "jdbc:mysql://localhost:3306/test";
// MySQL 8.0 以上版本 - JDBC 驅(qū)動(dòng)名及數(shù)據(jù)庫(kù) URL
static final String JDBC_DRIVER = "com.mysql.cj.jdbc.Driver";
static final String DB_URL = "jdbc:mysql://localhost:3306/test?useSSL=false&allowPublicKeyRetrieval=true&serverTimezone=UTC";
// 數(shù)據(jù)庫(kù)的用戶名與密碼,需要根據(jù)自己的設(shè)置
static final String USER = "root";
static final String PASS = "root";
public static void main(String[] args) {
Connection conn = null;
Statement stmt = null;
try {
// 注冊(cè) JDBC 驅(qū)動(dòng)
Class.forName(JDBC_DRIVER);
// 打開鏈接
System.out.println("連接數(shù)據(jù)庫(kù)...");
conn = DriverManager.getConnection(DB_URL, USER, PASS);
// 執(zhí)行查詢
System.out.println(" 實(shí)例化Statement對(duì)象...");
stmt = conn.createStatement();
String sql;
sql = "SELECT id, name, url FROM websites";
ResultSet rs = stmt.executeQuery(sql);
// 展開結(jié)果集數(shù)據(jù)庫(kù)
while (rs.next()) {
// 通過字段檢索
int id = rs.getInt("id");
String name = rs.getString("name");
String url = rs.getString("url");
// 輸出數(shù)據(jù)
System.out.print("ID: " + id);
System.out.print(", 站點(diǎn)名稱: " + name);
System.out.print(", 站點(diǎn) URL: " + url);
System.out.print("\n");
}
// 完成后關(guān)閉
rs.close();
stmt.close();
conn.close();
} catch (SQLException se) {
// 處理 JDBC 錯(cuò)誤
se.printStackTrace();
} catch (Exception e) {
// 處理 Class.forName 錯(cuò)誤
e.printStackTrace();
} finally {
// 關(guān)閉資源
try {
if (stmt != null) stmt.close();
} catch (SQLException se2) {
}// 什么都不做
try {
if (conn != null) conn.close();
} catch (SQLException se) {
se.printStackTrace();
}
}
System.out.println("Goodbye!");
}
}
運(yùn)行結(jié)果如下:
版本二
代碼演示
package com.ambow.druid;
import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.pool.DruidPooledConnection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
/*
方式一: 直接創(chuàng)建DruidDataSource ,然后設(shè)置屬性
*/
public class DruidDemo {
public static void main(String[] args) throws SQLException {
DruidDataSource dds = new DruidDataSource();
dds.setDriverClassName("com.mysql.cj.jdbc.Driver");
dds.setUrl("jdbc:mysql://localhost:3306/test?serverTimezone=UTC");
dds.setUsername("root");
dds.setPassword("root");
dds.setInitialSize(5);//初識(shí)連接數(shù)
dds.setMaxActive(10);//最大連接數(shù)
dds.setMaxWait(3000);//最大等待時(shí)間
//獲取連接
DruidPooledConnection connection = dds.getConnection();
System.out.println(connection);
//獲取執(zhí)行語(yǔ)句對(duì)象
String sql = "select * from websites";
PreparedStatement pstmt = connection.prepareStatement(sql);
//獲取結(jié)果集
ResultSet rs = pstmt.executeQuery();
while (rs.next()){
System.out.println(rs.getInt(1) + "-" + rs.getString(2) + "-" +
rs.getString(3) + "-" + rs.getInt(4) + "-" + rs.getString(5));
}
/*
jdbc連接的四個(gè)參數(shù):
driver
url
username
password
*/
}
}
?運(yùn)行結(jié)果:
2.3 方式二 配置文件的形式加載
- ?導(dǎo)入jar包 mysql-connection-java.jar、druid-1.1.12.jar
- ?定義配置文件
- ?加載配置文件
- ?獲取數(shù)據(jù)庫(kù)連接池對(duì)象
- ?獲取連接
此處的代碼實(shí)現(xiàn),首先也需要先將druid的jar包放到項(xiàng)目下的lib下并添加為庫(kù)文件,與前面一樣的形式創(chuàng)建。
2.3.1 在src目錄之下創(chuàng)建配置文件
文件名稱為:?druid.properties
PS:Java里面的配置文件為properties類型
2.3.2 在配置文件當(dāng)中添加如下的信息
將用戶以及密碼哪些信息寫入配置文件?
此處為8.0以上版本的書寫方法
driverClassName=com.mysql.cj.jdbc.Driver
url=jdbc:mysql:///test?serverTimezone=UTC
username=root
password=root
# 初始化連接數(shù)量
initialSize=5
# 最大連接數(shù)
maxActive=10
# 最大等待時(shí)間
maxWait=3000
以下為5.1?版本的寫法【舉例如下】
driverClassName=com.mysql.cj.jdbc.Driver
url=jdbc:mysql://182.168.1.1/test
username=root
password=root
# ???????
initialSize=5
# ?????
maxActive=10
# ??????
maxWait=3000
//前面的是IP地址以及數(shù)據(jù)庫(kù)的名稱
2.3.3 創(chuàng)建一個(gè)demo2的Java文件
?
?2.3.4 編輯Java代碼
此處只是一個(gè)獲取連接的代碼?
package com.ambow.druid;
import com.alibaba.druid.pool.DruidDataSourceFactory;
import javax.sql.DataSource;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.util.Properties;
/*
方式二:提取配置文件(把連接數(shù)據(jù)庫(kù)的參數(shù),抽取出來)
*/
public class DruidDemo2 {
public static void main(String[] args) throws Exception {
//獲取當(dāng)前項(xiàng)目的根目錄
System.out.println(System.getProperty("user.dir"));
// 加載配置文件
Properties prop = new Properties();
//FileInputStream is = new FileInputStream("src/druid.properties");
InputStream is = ClassLoader.getSystemClassLoader().getResourceAsStream("druid.properties");
prop.load(is);
// 獲取數(shù)據(jù)庫(kù)連接池對(duì)象
DataSource ds = DruidDataSourceFactory.createDataSource(prop);
// 獲取連接
Connection connection = ds.getConnection();
System.out.println(connection);
}
}
運(yùn)行結(jié)果:
?注意:
System.getProperty("user.dir"),在web項(xiàng)目,返回值就不是項(xiàng)目的根目錄了,而是tomcat的bin目錄。
三 在IDEA上創(chuàng)建Maven項(xiàng)目來實(shí)現(xiàn)上述的功能
3.1?創(chuàng)建項(xiàng)目
在file里面選擇創(chuàng)建新的項(xiàng)目,選擇Maven項(xiàng)目
?填寫項(xiàng)目的名稱,以及公司名稱
?點(diǎn)擊finsh即可。
此處補(bǔ)全一個(gè)資源文件夾
?3.2 創(chuàng)建一個(gè)Java類
?3.3 編輯Java代碼和配置文件
編輯配置文件的方法與2.3.2 一樣,此處不再贅述。?
在剛才的類里面編輯Java代碼
package com.ambow.druid;
import java.sql.*;
import java.util.Scanner;
public class App {
static final String JDBC_DRIVER="com.mysql.cj.jdbc.Driver";
static final String DB_URL="jdbc:mysql://localhost:3306/test";
static final String USER = "root";
static final String PASS ="root";
static Scanner sc =new Scanner(System.in);//成為類成員前面加入static修飾
public static void main(String[] args) throws SQLException {
// DruidDataSource dds = new DruidDataSource();
// dds.setDriverClassName("com.mysql.jdbc.Driver");
// dds.setUrl("jdbc:mysql://192.168.127.100:3306/db2");
// dds.setUsername("root");
// dds.setPassword("Admin2023!");
// dds.setInitialSize(5);
// dds.setMaxActive(10);
// dds.setMaxWait(3000);
// DruidPooledConnection connection = dds.getConnection();
// System.out.println(connection);
//加入循環(huán)
while (true) {
System.out.println("***********************************");
System.out.println("*********** 站點(diǎn)管理系統(tǒng) ***********");
System.out.println("*********** 1.新增站點(diǎn) ***********");
System.out.println("*********** 2.修改站點(diǎn) ***********");
System.out.println("*********** 3.刪除站點(diǎn) ***********");
System.out.println("*********** 4.查詢站點(diǎn) ***********");
System.out.println("*********** 0.退出系統(tǒng) ***********");
System.out.println("**********************************");
System.out.println("請(qǐng)選擇:");
//靜態(tài)方法只能訪問靜態(tài)變量
int choose = sc.nextInt();
switch (choose){
case 1:
addWebSite();
break;
case 2:
modifyWebSite();
break;
case 3:
dropWebSite();
break;
case 4:
queryWebSite();
break;
case 0:
System.out.println("退出系統(tǒng)");
System.exit(0);
break;
default:
System.out.println("對(duì)不起,您的選擇有誤!");
break;
}
}
}
// String sql ="select * from websites";
// PreparedStatement pstmt =connection.prepareStatement(sql);
// ResultSet rs = pstmt.executeQuery();
// while (rs.next()){
// System.out.println(rs.getInt(1) +"-"+ rs.getString(2) +"-"+ rs.getString(3)
// +"-"+ rs.getInt(4) +"-"+ rs.getString(5));
// }
// rs.close();
// pstmt.close();
// connection.close();
// }
private static void addWebSite() {
System.out.println("請(qǐng)輸入站點(diǎn)名稱:");
String name = sc.next();
System.out.println("請(qǐng)輸入站點(diǎn)URL:");
String url = sc.next();
System.out.println("請(qǐng)輸入站點(diǎn)alexa:");
int alexa = sc.nextInt();
System.out.println("請(qǐng)輸入站點(diǎn)所屬國(guó)家:");
String country = sc.next();
Connection conn = null;
PreparedStatement pstmt = null;
try {
Class.forName((JDBC_DRIVER));
conn = DriverManager.getConnection(DB_URL, USER, PASS);
String sql ="insert into websites values(null,?,?,?,?)";
pstmt = conn.prepareStatement(sql);
pstmt.setString(1,name);
pstmt.setString(2,url);
pstmt.setInt(3,alexa);
pstmt.setString(4,country);
pstmt.executeUpdate();
System.out.println("添加站點(diǎn)成功!");
}catch (SQLException se){
se.printStackTrace();
}catch (Exception e){
e.printStackTrace();
}finally {
try{
if(pstmt!=null) pstmt.close();
}catch (SQLException se2){
}
try{
if(conn!=null) conn.close();
}catch (SQLException se){
se.printStackTrace();
}
}
}
private static void modifyWebSite() {
System.out.println("請(qǐng)輸入要修改的站點(diǎn)名稱:");
String name = sc.next();
System.out.println("請(qǐng)輸入新站點(diǎn)URL:");
String url = sc.next();
System.out.println("請(qǐng)輸入新站點(diǎn)alexa:");
int alexa = sc.nextInt();
System.out.println("請(qǐng)輸入新站點(diǎn)所屬國(guó)家:");
String country = sc.next();
Connection conn = null;
PreparedStatement pstmt = null;
try {
Class.forName((JDBC_DRIVER));
conn = DriverManager.getConnection(DB_URL, USER, PASS);
String sql ="update websites set url=?,alexa= ?,country=? where name=?";
pstmt = conn.prepareStatement(sql);
pstmt.setString(1,name);
pstmt.setString(2,url);
pstmt.setInt(3,alexa);
pstmt.setString(4,country);
pstmt.executeUpdate();
System.out.println("修改站點(diǎn)成功!");
}catch (SQLException se){
se.printStackTrace();
}catch (Exception e){
e.printStackTrace();
}finally {
try{
if(pstmt!=null) pstmt.close();
}catch (SQLException se2){
}
try{
if(conn!=null) conn.close();
}catch (SQLException se){
se.printStackTrace();
}
}
}
private static void dropWebSite() {
System.out.println("請(qǐng)輸入要?jiǎng)h除的站點(diǎn)名稱:");
String name = sc.next();
// System.out.println("請(qǐng)輸入站點(diǎn)URL:");
// String url = sc.next();
// System.out.println("請(qǐng)輸入站點(diǎn)alexa:");
// int alexa = sc.nextInt();
// System.out.println("請(qǐng)輸入站點(diǎn)所屬國(guó)家:");
// String country = sc.next();
Connection conn = null;
PreparedStatement pstmt = null;
try {
Class.forName((JDBC_DRIVER));
conn = DriverManager.getConnection(DB_URL, USER, PASS);
String sql ="delete from websites where name=?";
pstmt = conn.prepareStatement(sql);
pstmt.setString(1,name);
// pstmt.setString(2,url);
// pstmt.setInt(3,alexa);
// pstmt.setString(4,country);
pstmt.executeUpdate();
System.out.println("刪除站點(diǎn)成功!");
}catch (SQLException se){
se.printStackTrace();
}catch (Exception e){
e.printStackTrace();
}finally {
try{
if(pstmt!=null) pstmt.close();
}catch (SQLException se2){
}
try{
if(conn!=null) conn.close();
}catch (SQLException se){
se.printStackTrace();
}
}
}
private static void queryWebSite() {
// System.out.println("請(qǐng)輸入要查詢的站點(diǎn)名稱:");
// String name = sc.next("name");
// System.out.println("請(qǐng)輸入站點(diǎn)URL:");
// String url = sc.next("url");
// System.out.println("請(qǐng)輸入站點(diǎn)alexa:");
// int alexa = sc.nextInt(Integer.parseInt("alexa"));
// System.out.println("請(qǐng)輸入站點(diǎn)所屬國(guó)家:");
// String country = sc.next("country");
Connection conn = null;
PreparedStatement pstmt = null;
try {
Class.forName((JDBC_DRIVER));
conn = DriverManager.getConnection(DB_URL, USER, PASS);
Statement stmt = conn.createStatement();
String sql ="SELECT id,name,url FROM websites";
ResultSet rs = stmt.executeQuery(sql);
//pstmt = conn.prepareStatement(sql);
// pstmt.setString(name);
// pstmt.setString(2,url);
// pstmt.setInt(3,alexa);
// pstmt.setString(4,country);
// System.out.print("name");
// System.out.print("url");
// System.out.print("alexa");
// System.out.print("country");
// System.out.print("\n");
//pstmt.executeQuery();
// System.out.println("查詢站點(diǎn)成功!");
while (rs.next()){
int id =rs.getInt("id");
String name = rs.getString("name");
String url = rs.getString("url");
System.out.print("id"+":"+id+"-");
System.out.print("name"+":"+name+"-");
System.out.print("url"+":"+url);
System.out.print("\n");
System.out.println("查詢站點(diǎn)成功!");
}
rs.close();
stmt.close();
conn.close();
}catch (SQLException se){
se.printStackTrace();
}catch (Exception e){
e.printStackTrace();
}finally {
try{
if(pstmt!=null) pstmt.close();
}catch (SQLException se2){
}
try{
if(conn!=null) conn.close();
}catch (SQLException se){
se.printStackTrace();
}
}
}
}
運(yùn)行結(jié)果如下:
?
查看MySQL里面的表信息可以看到信息添加成功了。?
?
?修改站點(diǎn)信息
?刪除站點(diǎn)
?刪除之后的恢復(fù)為原來的情況
最后退出系統(tǒng)。
3.4 Java代碼模塊講解
3.4.1 Java Scanner 類
java.util.Scanner 是 Java5 的新特征,我們可以通過 Scanner 類來獲取用戶的輸入。
下面是創(chuàng)建 Scanner 對(duì)象的基本語(yǔ)法:
Scanner s = new Scanner(System.in);
Scanner 類的 next() 與 nextLine() 方法獲取輸入的字符串,在讀取數(shù)據(jù)前我們一般需要 使用 hasNext 與 hasNextLine 判斷是否還有輸入的數(shù)據(jù)。
next() 、nextInt() 、nextLine() 區(qū)別
next():
- 1、一定要讀取到有效字符后才可以結(jié)束輸入。
- 2、對(duì)輸入有效字符之前遇到的空白,next() 方法會(huì)自動(dòng)將其去掉。
- 3、只有輸入有效字符后才將其后面輸入的空白作為分隔符或者結(jié)束符。
- next() 不能得到帶有空格的字符串。
nextLine():
- 1、以Enter為結(jié)束符,也就是說 nextLine()方法返回的是輸入回車之前的所有字符。
- 2、可以獲得空白。
如果要輸入 int 或 float 類型的數(shù)據(jù),在 Scanner 類中也有支持,但是在輸入之前最好先使用 hasNextXxx() 方法進(jìn)行驗(yàn)證,再使用 nextXxx() 來讀取。
nextInt()、nextLine()區(qū)別:
- 1.nextInt()只會(huì)讀取數(shù)值,剩下"\n"還沒有讀取,并將cursor放在本行中。
- 2.nextLine()會(huì)讀取"\n",并結(jié)束(nextLine() reads till the end of line \n)。
- 3.如果想要在nextInt()后讀取一行,就得在nextInt()之后額外加上cin.nextLine()
nextInt() 一定要讀取到有效字符后才可以結(jié)束輸入,對(duì)輸入有效字符之前遇到的空格鍵、Tab鍵或Enter鍵等結(jié)束符,nextInt() 方法會(huì)自動(dòng)將其去掉,只有在輸入有效字符之后,nextInt()方法才將其后輸入的空格鍵、Tab鍵或Enter鍵等視為分隔符或結(jié)束符。簡(jiǎn)單地說,nextInt()查找并返回來自此掃描器的下一個(gè)完整標(biāo)記。完整標(biāo)記的前后是與分隔模式匹配的輸入信息,所以next方法不能得到帶空格的字符串。
??而nextLine() 方法的結(jié)束符只是Enter鍵,即nextLine() 方法返回的是Enter鍵之前的所有字符,它是可以得到帶空格的字符串的。
??可以看到,nextLine() 自動(dòng)讀取了被nextInt() 去掉的Enter作為他的結(jié)束符,所以沒辦法給s2從鍵盤輸入值。經(jīng)過驗(yàn)證,我發(fā)現(xiàn)其他的next的方法,如double nextDouble() , float nextFloat() , int nextInt() 等與nextLine() 連用時(shí)都存在這個(gè)問題,解決的辦法是:在每一個(gè) next() 、nextDouble() 、 nextFloat()、nextInt() 等語(yǔ)句之后加一個(gè)nextLine() 語(yǔ)句,將被next() 去掉的Enter結(jié)束符過濾掉。
此處使用的是scanner對(duì)象的nextInt()方法,使用switch-case分支進(jìn)行判斷需要執(zhí)行的選項(xiàng)是那個(gè)。
Scanner sc =new Scanner(System.in);
int choose = sc.nextInt();
switch (choose){
case 1:
addWebSite();
break;
case 2:
modifyWebSite();
break;
case 3:
dropWebSite();
break;
case 4:
queryWebSite();
break;
case 0:
System.out.println("退出系統(tǒng)");
System.exit(0);
break;
default:
System.out.println("對(duì)不起,您的選擇有誤!");
break;
}
在新定義的方法上面按住alt+回車既可以出現(xiàn)快捷方式,點(diǎn)擊第一個(gè)創(chuàng)建一個(gè)方法。?
?創(chuàng)建完成之后新增while(true)讓程序可以一直執(zhí)行,程序的中斷將會(huì)由輸入的0來決定退出去。
?完整的這一塊代碼
public static void main(String[] args) throws SQLException {
while (true) {
System.out.println("***********************************");
System.out.println("*********** 站點(diǎn)管理系統(tǒng) ***********");
System.out.println("*********** 1.新增站點(diǎn) ***********");
System.out.println("*********** 2.修改站點(diǎn) ***********");
System.out.println("*********** 3.刪除站點(diǎn) ***********");
System.out.println("*********** 4.查詢站點(diǎn) ***********");
System.out.println("*********** 0.退出系統(tǒng) ***********");
System.out.println("**********************************");
System.out.println("請(qǐng)選擇:");
Scanner sc =new Scanner(System.in);
int choose = sc.nextInt();
switch (choose){
case 1:
addWebSite();
break;
case 2:
modifyWebSite();
break;
case 3:
dropWebSite();
break;
case 4:
queryWebSite();
break;
case 0:
System.out.println("退出系統(tǒng)");
System.exit(0);
break;
default:
System.out.println("對(duì)不起,您的選擇有誤!");
break;
}
}
}
3.4.2 系統(tǒng)添加數(shù)據(jù)模塊方法
例如以下的方法
private static void dropWebSite() {
System.out.println("請(qǐng)輸入要?jiǎng)h除的站點(diǎn)名稱:");
//sc.next方法將不會(huì)用到
//前面設(shè)置的sc變量是只能在main方法里面使用,要想使用需要將sc變量放在外面使用
}
解決方法:將sc變量放在main方法外面即可。變成整個(gè)類的作用方法
?雖然提出來了,但是scanner的方法仍然不能使用,會(huì)出錯(cuò),原因是sc為成員變量,main是靜態(tài)的方法,靜態(tài)的方法只能訪問靜態(tài)的方法,不能訪問類里面的變量,需要將scanner變成一個(gè)靜態(tài)的變量。
加入關(guān)鍵字static即可訪問其方法
?
?接下來繼續(xù)編寫方法原來實(shí)現(xiàn)相關(guān)功能
3.4.3? 編輯MySQL與druid依賴
官方的網(wǎng)站鏈接如下:
Maven Repository: Search/Browse/Explore (mvnrepository.com)
在官方網(wǎng)站里面直接搜素需要的依賴即可
?選擇mysql搜素,選擇訪問比較多的即可
?紅色框住的是8.0版本以上的,選擇自己的對(duì)應(yīng)版本即可。此處小編的版本為8.0的版本,選擇這個(gè)即可
?
?點(diǎn)擊此處藍(lán)色框住的部分即可復(fù)制,出現(xiàn)紅色的提示即是復(fù)制成功
?代碼部分
<dependencies>
<dependency>
<groupId>com.mysql</groupId>
<artifactId>mysql-connector-j</artifactId>
<version>8.0.31</version>
</dependency>
</dependencies>
?粘貼過來的顯示為紅色,如果之前未安裝此組件的話,會(huì)有一個(gè)刷新的圖標(biāo),點(diǎn)擊一下,完成安裝,安裝完成之后紅色部分會(huì)變成白色。
?
出現(xiàn)這種情況既是安裝完成。?
搜索druid依賴,點(diǎn)擊第一個(gè)即可
?選擇自己的對(duì)應(yīng)版本
?
?代碼部分如下:
<!-- https://mvnrepository.com/artifact/com.alibaba/druid -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.2.8</version>
</dependency>
粘貼上述代碼即可。
3.4.4 編輯插入數(shù)據(jù)方法
前面先給用戶一個(gè)輸入?yún)^(qū),并且將輸入的內(nèi)容編輯為相關(guān)的變量暫時(shí)存在內(nèi)存區(qū),此時(shí)的數(shù)據(jù)并沒有保存到數(shù)據(jù)庫(kù)里面。
下面加入配置文件原來訪問數(shù)據(jù)庫(kù),設(shè)置與前面的2.3.2 編輯配置文件相同。
利用類加載器原來加載配置文件,讓文件以流的形式讀進(jìn)來,
選擇alt+enter,選擇第二個(gè),讓異常拋出
此處還有異常,將異常的這段代碼放在try-catch里面捕獲一下拋出
?這樣捕獲異常
?
捕獲完成之后會(huì)自動(dòng)放在catch語(yǔ)句里面?
// 加載配置文件
Properties prop = new Properties();
InputStream is = ClassLoader.getSystemClassLoader().getResourceAsStream("druid.properties");
try {
prop.load(is);
// 獲取數(shù)據(jù)庫(kù)連接池對(duì)象
DataSource ds = DruidDataSourceFactory.createDataSource(prop);
// 獲取連接
Connection connection = ds.getConnection();
} catch (IOException e) {
e.printStackTrace();
} catch (SQLException throwables) {
throwables.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
此處創(chuàng)建一個(gè)預(yù)編譯對(duì)象
?完成之后使用其方法獲取相關(guān)的數(shù)據(jù),將其插入到數(shù)據(jù)庫(kù)里面。
完整的插入代碼
private static void addWebSite() {
System.out.println("請(qǐng)輸入站點(diǎn)名稱:");
String name = sc.next();
System.out.println("請(qǐng)輸入站點(diǎn)URL:");
String url = sc.next();
System.out.println("請(qǐng)輸入站點(diǎn)alexa:");
int alexa = sc.nextInt();
System.out.println("請(qǐng)輸入站點(diǎn)所屬國(guó)家:");
String country = sc.next();
// 1 加載配置文件
Properties prop = new Properties();
InputStream is = ClassLoader.getSystemClassLoader().getResourceAsStream("druid.properties");
try {
prop.load(is);
// 2 獲取數(shù)據(jù)庫(kù)連接池對(duì)象
DataSource ds = DruidDataSourceFactory.createDataSource(prop);
// 3 獲取連接
Connection connection = ds.getConnection();
// 4 執(zhí)行SQL
//插入SQL語(yǔ)句,?為占位符
String sql ="insert into websites values(null,?,?,?,?)";
//創(chuàng)建PreparedStatement預(yù)編譯執(zhí)行對(duì)象,將傳入的SQL語(yǔ)句讀出來。
PreparedStatement stmt = connection.prepareStatement(sql);
//設(shè)置參數(shù)
stmt.setString(1,name);
stmt.setString(2,url);
stmt.setInt(3,alexa);
stmt.setString(4,country);
stmt.executeUpdate();
// 獲取插入完成的值,一般插入完成之后會(huì)出現(xiàn)·插入影響的行數(shù)
// 將返回變量的類型設(shè)置為int型
int row = stmt.executeUpdate();
//提示一下
if (row != 0){
System.out.println("添加站點(diǎn)成功!");
}
} catch (IOException e) {
e.printStackTrace();
} catch (SQLException throwables) {
throwables.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
3.4.5 編輯查詢代碼
PS:此處為未經(jīng)優(yōu)化的代碼段 ,后續(xù)有優(yōu)化之后的代碼段。
在上述的插入代碼的基礎(chǔ)之上編輯查詢代碼即可。
private static void queryWebSite() {
// 1 加載配置文件
Properties prop = new Properties();
InputStream is = ClassLoader.getSystemClassLoader().getResourceAsStream("druid.properties");
try {
prop.load(is);
// 2 獲取數(shù)據(jù)庫(kù)連接池對(duì)象
DataSource ds = DruidDataSourceFactory.createDataSource(prop);
// 3 獲取連接
Connection connection = ds.getConnection();
// 4 執(zhí)行SQL
//插入SQL語(yǔ)句,?為占位符
String sql ="select * from websites";
//創(chuàng)建PreparedStatement預(yù)編譯執(zhí)行對(duì)象,將傳入的SQL語(yǔ)句讀出來。
PreparedStatement stmt = connection.prepareStatement(sql);
//設(shè)置返回的參數(shù),此處的返回值為結(jié)果集
ResultSet rs = stmt.executeQuery();
// 獲取查詢到的結(jié)果集
while (rs.next()){
// 將結(jié)果集拼接起來
System.out.println(rs.getInt(1) + "-" + rs.getString(2) + "-" + rs.getString(3)
+ "-" + rs.getInt(4) + "-" + rs.getString(5));
}
} catch (IOException e) {
e.printStackTrace();
} catch (SQLException throwables) {
throwables.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
此處的獲取數(shù)據(jù)庫(kù)連接可以創(chuàng)建一個(gè)DruidUtil類來專門獲取數(shù)據(jù)庫(kù)連接
工具類的完整代碼【此處就是將獲取數(shù)據(jù)庫(kù)連接的部分一一個(gè)類的形式創(chuàng)建,此時(shí)可以優(yōu)化一下之前的代碼】
優(yōu)化之后的插入數(shù)據(jù)代碼
private static void addWebSite() {
System.out.println("請(qǐng)輸入站點(diǎn)名稱:");
String name = sc.next();
System.out.println("請(qǐng)輸入站點(diǎn)URL:");
String url = sc.next();
System.out.println("請(qǐng)輸入站點(diǎn)alexa:");
int alexa = sc.nextInt();
System.out.println("請(qǐng)輸入站點(diǎn)所屬國(guó)家:");
String country = sc.next();
try {
// 3 獲取連接,此處使用類方法進(jìn)行調(diào)用。
Connection connection = DruidUtil.getConn();
// 4 執(zhí)行SQL
//插入SQL語(yǔ)句,?為占位符
String sql ="insert into websites values(null,?,?,?,?)";
//創(chuàng)建PreparedStatement預(yù)編譯執(zhí)行對(duì)象,將傳入的SQL語(yǔ)句讀出來。
PreparedStatement stmt = connection.prepareStatement(sql);
//設(shè)置參數(shù)
stmt.setString(1,name);
stmt.setString(2,url);
stmt.setInt(3,alexa);
stmt.setString(4,country);
stmt.executeUpdate();
// 獲取插入完成的值,一般插入完成之后會(huì)出現(xiàn)·插入影響的行數(shù)
// 將返回變量的類型設(shè)置為int型
int row = stmt.executeUpdate();
//提示一下
if (row != 0){
System.out.println("添加站點(diǎn)成功!");
}
// 原先的異常處理也就不再需要,直接刪除即可
} catch (SQLException throwables) {
throwables.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
優(yōu)化之后的查詢代碼
private static void queryWebSite() {
try {
// 3 獲取連接
Connection connection = DruidUtil.getConn();
// 4 執(zhí)行SQL
//插入SQL語(yǔ)句,?為占位符
String sql ="select * from websites";
//創(chuàng)建PreparedStatement預(yù)編譯執(zhí)行對(duì)象,將傳入的SQL語(yǔ)句讀出來。
PreparedStatement stmt = connection.prepareStatement(sql);
//設(shè)置返回的參數(shù),此處的返回值為結(jié)果集
ResultSet rs = stmt.executeQuery();
// 獲取查詢到的結(jié)果集
while (rs.next()){
// 將結(jié)果集拼接起來
System.out.println(rs.getInt(1) + "-" + rs.getString(2) + "-" + rs.getString(3)
+ "-" + rs.getInt(4) + "-" + rs.getString(5));
}
} catch (SQLException throwables) {
throwables.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
3.4.6? 完整的優(yōu)化后的代碼
package com.ambow.druid;
import java.sql.*;
import java.util.Scanner;
public class work01 {
static Scanner sc =new Scanner(System.in);
public static void main(String[] args){
while(true) {
System.out.println("***********************************");
System.out.println("*********** 站點(diǎn)管理系統(tǒng) ***********");
System.out.println("*********** 1.新增站點(diǎn) ***********");
System.out.println("*********** 2.修改站點(diǎn) ***********");
System.out.println("*********** 3.刪除站點(diǎn) ***********");
System.out.println("*********** 4.查詢站點(diǎn) ***********");
System.out.println("*********** 0.退出系統(tǒng) ***********");
System.out.println("**********************************");
System.out.println("請(qǐng)選擇:");
Scanner sc = new Scanner(System.in);
int choose = sc.nextInt();
switch (choose) {
case 1:
addWebSite();
break;
case 2:
modifyWebSite();
break;
case 3:
dropWebSite();
break;
case 4:
queryWebSite();
break;
case 0:
System.out.println("退出系統(tǒng)");
System.exit(0);
break;
default:
System.out.println("對(duì)不起,您的選擇有誤!");
break;
}
}
}
private static void addWebSite() {
System.out.println("請(qǐng)輸入站點(diǎn)名稱:");
String name = sc.next();
System.out.println("請(qǐng)輸入站點(diǎn)URL:");
String url = sc.next();
System.out.println("請(qǐng)輸入站點(diǎn)alexa:");
int alexa = sc.nextInt();
System.out.println("請(qǐng)輸入站點(diǎn)所屬國(guó)家:");
String country = sc.next();
try {
// 3 獲取連接,此處使用類方法進(jìn)行調(diào)用。
Connection connection = DruidUtil.getConn();
// 4 執(zhí)行SQL
//插入SQL語(yǔ)句,?為占位符
String sql ="insert into websites values(null,?,?,?,?)";
//創(chuàng)建PreparedStatement預(yù)編譯執(zhí)行對(duì)象,將傳入的SQL語(yǔ)句讀出來。
PreparedStatement stmt = connection.prepareStatement(sql);
//設(shè)置參數(shù)
stmt.setString(1,name);
stmt.setString(2,url);
stmt.setInt(3,alexa);
stmt.setString(4,country);
stmt.executeUpdate();
// 獲取插入完成的值,一般插入完成之后會(huì)出現(xiàn)·插入影響的行數(shù)
// 將返回變量的類型設(shè)置為int型
int row = stmt.executeUpdate();
//提示一下
if (row != 0){
System.out.println("添加站點(diǎn)成功!");
}
// 原先的異常處理也就不再需要,直接刪除即可
} catch (SQLException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
private static void modifyWebSite() {
System.out.println("請(qǐng)輸入要修改的站點(diǎn)名稱:");
String name = sc.next();
System.out.println("請(qǐng)輸入新站點(diǎn)URL:");
String url = sc.next();
System.out.println("請(qǐng)輸入新站點(diǎn)alexa:");
int alexa = sc.nextInt();
System.out.println("請(qǐng)輸入新站點(diǎn)所屬國(guó)家:");
String country = sc.next();
try {
// 3 獲取連接
Connection connection = DruidUtil.getConn();
// 4 執(zhí)行SQL
//插入SQL語(yǔ)句,?為占位符
String sql ="update websites set url=?,alexa= ?,country=? where name=?";
//創(chuàng)建PreparedStatement預(yù)編譯執(zhí)行對(duì)象,將傳入的SQL語(yǔ)句讀出來。
PreparedStatement stmt = connection.prepareStatement(sql);
//設(shè)置參數(shù)
stmt = connection.prepareStatement(sql);
stmt.setString(1,name);
stmt.setString(2,url);
stmt.setInt(3,alexa);
stmt.setString(4,country);
stmt.executeUpdate();
int row = stmt.executeUpdate();
//提示一下
if (row != 0){
System.out.println("修改站點(diǎn)成功!");
}
} catch (SQLException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
private static void dropWebSite() {
System.out.println("請(qǐng)輸入要?jiǎng)h除的站點(diǎn)名稱:");
String name = sc.next();
try {
// 3 獲取連接
Connection connection = DruidUtil.getConn();
// 4 執(zhí)行SQL
//插入SQL語(yǔ)句,?為占位符
String sql ="delete from websites where name=?";
//創(chuàng)建PreparedStatement預(yù)編譯執(zhí)行對(duì)象,將傳入的SQL語(yǔ)句讀出來。
PreparedStatement stmt = connection.prepareStatement(sql);
//設(shè)置參數(shù)
stmt.setString(1,name);
stmt.executeUpdate();
// 獲取插入完成的值,一般插入完成之后會(huì)出現(xiàn)·插入影響的行數(shù)
// 將返回變量的類型設(shè)置為int型
int row = stmt.executeUpdate();
//提示一下
if (row != 0){
System.out.println("刪除站點(diǎn)成功!");
}
} catch (SQLException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
private static void queryWebSite() {
try {
// 3 獲取連接
Connection connection = DruidUtil.getConn();
// 4 執(zhí)行SQL
//插入SQL語(yǔ)句,?為占位符
String sql ="select * from websites";
//創(chuàng)建PreparedStatement預(yù)編譯執(zhí)行對(duì)象,將傳入的SQL語(yǔ)句讀出來。
PreparedStatement stmt = connection.prepareStatement(sql);
//設(shè)置返回的參數(shù),此處的返回值為結(jié)果集
ResultSet rs = stmt.executeQuery();
// 獲取查詢到的結(jié)果集
while (rs.next()){
// 將結(jié)果集拼接起來
System.out.println(rs.getInt(1) + "-" + rs.getString(2) + "-" + rs.getString(3)
+ "-" + rs.getInt(4) + "-" + rs.getString(5));
}
} catch (SQLException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
}
思考——如何優(yōu)化上述的Java代碼??
優(yōu)化方案——使用分層將代碼分為幾個(gè)模塊
1、視圖層
2、持久層 / 數(shù)據(jù)訪問層 Dao -- Data? Access? Object? 數(shù)據(jù)訪問層
優(yōu)化的方案將會(huì)在后續(xù)的文章當(dāng)中給出具體的操作。
jdbc是硬編碼的方式
SQL語(yǔ)句也是硬編碼,缺點(diǎn)是不易維護(hù)
?mybatis框架
總結(jié)
以上就是今天的內(nèi)容~
歡迎大家點(diǎn)贊??,收藏?,轉(zhuǎn)發(fā)??,
如有問題、建議,請(qǐng)您在評(píng)論區(qū)留言??哦。文章來源:http://www.zghlxwxcb.cn/news/detail-758607.html
最后:轉(zhuǎn)載請(qǐng)注明出處?。?!文章來源地址http://www.zghlxwxcb.cn/news/detail-758607.html
到了這里,關(guān)于IDEA項(xiàng)目實(shí)踐——?jiǎng)?chuàng)建Java項(xiàng)目以及創(chuàng)建Maven項(xiàng)目案例、使用數(shù)據(jù)庫(kù)連接池創(chuàng)建項(xiàng)目簡(jiǎn)介的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!