Java連接MySQL數(shù)據(jù)庫(kù)實(shí)例
首先說明,由于是8版本的數(shù)據(jù)庫(kù),所以配置類的寫法上與5版本的有所區(qū)別,需要注意,同時(shí)用idea或eclipse時(shí)需要導(dǎo)入jar包,jar包的下載鏈接:
https://dev.mysql.com/get/archives/mysql-connector-java-8.0/mysql-connector-java-8.0.28.zip
如果想要下載8版本不同的jar包只需要修改8.0.28為指定版本即可。
idea導(dǎo)入jar包的方法如下:
然后是代碼部分,首先先建表:
CREATE TABLE `train_message` ( `id` int NOT NULL AUTO_INCREMENT COMMENT '主鍵id', `train_name` varchar(20) NOT NULL COMMENT '列車名', `origin` varchar(30) NOT NULL COMMENT '始發(fā)地', `terminal` varchar(30) NOT NULL COMMENT '終到地', `departure_time` timestamp NOT NULL COMMENT '出站時(shí)間', `state` varchar(10) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL DEFAULT '正常' COMMENT '列車狀態(tài)', PRIMARY KEY (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=9 DEFAULT CHARSET=utf8mb3
然后創(chuàng)建連接的配置類DbConfig.java,localhost是本機(jī)的ip地址,如果有服務(wù)器就填服務(wù)器的ip地址,message是數(shù)據(jù)庫(kù)的名字,這里一張圖說下有很多新手誤解的名字
import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; /** * 數(shù)據(jù)庫(kù)配置類 * @author 景苒 */ public class DbConfig { public Connection dbConfig() throws SQLException { try { Class.forName("com.mysql.cj.jdbc.Driver"); }catch (Exception e) { System.out.print("加載驅(qū)動(dòng)失敗!"); e.printStackTrace(); } String url = "jdbc:mysql://localhost:3306/message?useSSL=false&useUnicode=true&characterEncoding=utf-8&serverTimezone=GMT%2B8&allowPublicKeyRetrieval=true"; String user = "root"; String password = "123456"; return DriverManager.getConnection(url, user, password); } }
然后寫下主函數(shù)Main.java,這里主函數(shù)的函數(shù)體可以在最后再寫,需要什么功能就把注釋打開就好,快捷注釋的方法,選中這句話,按ctrl加/,就能全注釋了。
import java.sql.SQLException; /** * 主函數(shù),調(diào)用功能 * @author 景苒 */ public class Main { public static void main(String[] args) throws SQLException { // new GetMessage().getMessage(); // new UpdateTrainState().updateTrainState(); // new InsertTrain().insertTrain(); // new GetNumber().getNumber(); } }
然后是每個(gè)的功能:
1.查詢沈陽(yáng)到武漢的所有列車信息,按出發(fā)時(shí)間先后排序
建GetMessage.java類
import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; /** * 查詢沈陽(yáng)到武漢的所有列車信息,按出發(fā)時(shí)間先后排序 * @author 景苒 */ public class GetMessage { public void getMessage() throws SQLException { Connection con = new DbConfig().dbConfig(); String sql = "select * from `train_message` where origin = ? and terminal = ? ORDER BY departure_time ASC"; String origin = "沈陽(yáng)"; String terminal = "武漢"; PreparedStatement ps = con.prepareStatement(sql); ps.setString(1, origin); ps.setString(2, terminal); ResultSet rs = ps.executeQuery(); try { while (rs.next()) { System.out.println("列車名:" + rs.getString("train_name") + " 始發(fā)站:" + rs.getString("origin") + " 終到站:" + rs.getString("terminal") + " 出發(fā)時(shí)間:" + rs.getString("departure_time") + " 列車狀態(tài):" + rs.getString("state")); } }catch (SQLException e) { e.printStackTrace(); }finally { ps.close(); con.close(); } } }
2.修改T2255列車的狀態(tài)為停運(yùn)
建UpdateTrainState.java類
import java.sql.Connection; import java.sql.SQLException; import java.sql.Statement; /** * 修改T2255列車的狀態(tài)為停運(yùn) * @author 景苒 */ public class UpdateTrainState { public void updateTrainState() throws SQLException { Connection con = new DbConfig().dbConfig(); String sql = "UPDATE `train_message` SET state = '停運(yùn)' WHERE train_name = 'T2255'"; Statement statement = con.createStatement(); try { int i = statement.executeUpdate(sql); if (i > 0) { System.out.println("更新成功"); }else { System.out.println("更新失敗"); } }catch (SQLException e) { e.printStackTrace(); }finally { statement.close(); con.close(); } } }
3.新增一輛列車信息(自己輸入)
建InsertTrain.java類
import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.SQLException; import java.util.Scanner; /** * 新增一輛列車信息(自己輸入) * 始發(fā)時(shí)間為timestamp類型,輸入時(shí)需要確保格式正確,如:2019-01-01 00:00:00 * @author 景苒 */ public class InsertTrain { public void insertTrain() throws SQLException { Connection con = new DbConfig().dbConfig(); Scanner scanner = new Scanner(System.in); String sql = "insert into `train_message` values(null, ?, ?, ?, ?, default)"; System.out.print("請(qǐng)輸入列車名:"); String trainName = scanner.nextLine(); System.out.print("請(qǐng)輸入始發(fā)站:"); String origin = scanner.nextLine(); System.out.print("請(qǐng)輸入終到站:"); String terminal = scanner.nextLine(); System.out.print("請(qǐng)輸入始發(fā)時(shí)間:"); String departureTime = scanner.nextLine(); PreparedStatement ps = con.prepareStatement(sql); ps.setString(1, trainName); ps.setString(2, origin); ps.setString(3, terminal); ps.setString(4, departureTime); try { int i = ps.executeUpdate(); if (i > 0) { System.out.println("添加成功"); }else { System.out.println("添加失敗"); } }catch (SQLException e) { e.printStackTrace(); }finally { ps.close(); con.close(); } } }
4.查詢狀態(tài)為正常的列車數(shù)量
建GetNumber.java類
import java.sql.Statement; /** * 查詢狀態(tài)為正常的列車數(shù)量 * @author 景苒 */ public class GetNumber { public void getNumber() throws SQLException { Connection con = new DbConfig().dbConfig(); String sql = "select count(state) from `train_message` where state = '正常'"; Statement statement = con.createStatement(); try { ResultSet resultSet = statement.executeQuery(sql); while (resultSet.next()) { System.out.println("狀態(tài)為正常的列車數(shù)量為:" + resultSet.getInt(1)); } }catch (SQLException e){ e.printStackTrace(); }finally { statement.close(); con.close(); } } }
最后附上navicat的屬性結(jié)構(gòu)圖和樣例插入的語(yǔ)句
數(shù)據(jù)根據(jù)自己需求自行寫入幾個(gè)就行,以上就是java連接mysql數(shù)據(jù)庫(kù)的實(shí)例代碼,eclipse也大同小異,就導(dǎo)入jar包的方式不同。
到此這篇關(guān)于Java連接MySQL數(shù)據(jù)庫(kù)實(shí)例的文章就介紹到這了。希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
- 詳解Java使用JDBC連接MySQL數(shù)據(jù)庫(kù)
- MySQL數(shù)據(jù)庫(kù)?JDBC?編程(Java?連接?MySQL)
- Java連接Mysql數(shù)據(jù)庫(kù)詳細(xì)代碼實(shí)例
- Java連接mysql數(shù)據(jù)庫(kù)代碼實(shí)例程序
- Java使用jdbc連接MySQL數(shù)據(jù)庫(kù)實(shí)例分析
- java基于jdbc連接mysql數(shù)據(jù)庫(kù)功能實(shí)例詳解
- java連接MySQL數(shù)據(jù)庫(kù)的代碼
- JSP連接MySQL數(shù)據(jù)庫(kù)詳細(xì)步驟
相關(guān)文章
SpringBoot動(dòng)態(tài)數(shù)據(jù)源連接測(cè)試的操作詳解
這篇文章主要介紹了SpringBoot動(dòng)態(tài)數(shù)據(jù)源連接測(cè)試的操作步驟,文中通過代碼示例和圖文結(jié)合的方式給大家講解的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作有一定的幫助,需要的朋友可以參考下2024-03-03Spring Security OAuth2集成短信驗(yàn)證碼登錄以及第三方登錄
這篇文章主要介紹了Spring Security OAuth2集成短信驗(yàn)證碼登錄以及第三方登錄,小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過來(lái)看看吧2018-04-04Dubbo+Nacos服務(wù)啟動(dòng)報(bào)錯(cuò),返回unknown user的問題
這篇文章主要介紹了Dubbo+Nacos服務(wù)啟動(dòng)報(bào)錯(cuò),返回unknown user的問題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2023-09-09java使用MulticastSocket實(shí)現(xiàn)組播
這篇文章主要為大家詳細(xì)介紹了java使用MulticastSocket實(shí)現(xiàn)組播,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2019-01-01break和continue的作用和區(qū)別解析(案例分析)
break和continue都是用來(lái)控制循環(huán)結(jié)構(gòu)的,主要作用是停止循環(huán),這篇文章主要介紹了break和continue的作用和區(qū)別,需要的朋友可以參考下2023-03-03