原創不易,轉載請標明出處。上一篇《Java實驗--基於Swing的簡單的歌曲信息管理系統(一)》講解瞭如何這個小項目的具體情況和主要功能,下麵進入編碼階段。 在eclipse中新建java項目,項目的結構如下: 資料庫的設計 該項目簡單,只涉及到了兩種表,且沒有涉及到關聯查詢,就只是對單表進行操作。 ...
原創不易,轉載請標明出處。上一篇《Java實驗--基於Swing的簡單的歌曲信息管理系統(一)》講解瞭如何這個小項目的具體情況和主要功能,下麵進入編碼階段。
在eclipse中新建java項目,項目的結構如下:
- 資料庫的設計
該項目簡單,只涉及到了兩種表,且沒有涉及到關聯查詢,就只是對單表進行操作。
工具:使用的是XMAPP(LZ裝了好久的mysql沒有裝上,各種報錯,然後同學就推薦了這款集成工具)和Navicat。
步驟:
- 啟動XMAPP,然後啟動MySQL。如下圖所示:
2. 這裡沒有選擇用命令行來創建資料庫,而是直接在可視化工具navicat中新建(若使用,點擊XMAPP中的shell按鈕即可),資料庫名為songmanage,註意選擇編碼為utf8,新建兩張表,一張名為song,一張名為user。具體表的欄位如下:
user表(主鍵id,用戶名name,密碼password,類型role:1代表用戶、2代表管理員,roderby用來排序自增):
song表(主鍵id,歌曲名name,語言language,類別category,歌手名singer,orderby用來排序自增):
若使用命令行建資料庫:
# 創建資料庫
CREATE DATABASE 資料庫名;
# 創建表
CREATE TABLE 表名(
列名 數據類型 [NULL | NOT NULL],
........
);
- 實體類(entity包下)設計
- 用戶實體類:User.java
package shiyan6.entity; /** * 用戶實體類,其中的role用於分別是普通人員還是管理員 * */ public class User { private String id; private String name; private String password; private int role; // 用戶身份,1表示普通用戶,2表示管理員 // 無參構造器 public User() { } /** * 有參構造器 * @param id,使用util包下的Common.getUUID()來產生一個8位的uuid * @param name,用戶名 * @param password,登錄密碼 */ public User(String id, String name, String password,int role) { this.id = id; this.name = name; this.password = password; this.role = role; } // 各個屬性的set、get方法 .......... }View Code
2. 歌曲實體類:Song.java
package shiyan6.entity; /** * 歌曲實體類 * */ public class Song { private String id; // 編號 private String name; // 歌曲名 private String language; // 語言 private String category; // 類別 private String singer; // 歌手名 /** * 有參構造函數 * @param name * @param language * @param category * @param singer */ public Song(String id, String name, String language, String category, String singer) { this.id = id; this.name = name; this.language = language; this.category = category; this.singer = singer; } /** * 無參構造函數 */ public Song() { } // 各屬性的get、set方法 ............. }View Code
- jdbc.properties文件類容(資料庫配置信息)
# 資料庫的用戶名 jdbc.username=root # 資料庫的密碼 jdbc.password= # 資料庫驅動 jdbc.driver=com.mysql.jdbc.Driver # url jdbc.url=jdbc:mysql://127.0.0.1:3306/songmanage?characterEncoding=utf8
- JdbcUtil.java(獲取數據連接,util包下)
這裡需要註意的獲取資料庫配置文件時,路徑的問題。
InputStream inStream = JdbcUtil.class.getResourceAsStream("/shiyan6/jdbc.properties"); Properties prop = new Properties(); prop.load(inStream);
該文件完整代碼:
package shiyan6.util; import java.io.InputStream; import java.sql.Connection; import java.sql.DriverManager; import java.util.Properties; /** * 資料庫幫助類,主要用於獲取資料庫連接 * */ public class JdbcUtil { // 表示定義資料庫的用戶名 private static String USERNAME; // 定義資料庫的密碼 private static String PASSWORD; // 定義資料庫的驅動信息 private static String DRIVER; // 定義訪問資料庫的地址 private static String URL; // 定義資料庫的連接 private static Connection connection; /** * 靜態載入資料庫配置信息,並給相關的屬性賦值 */ static { try { InputStream inStream = JdbcUtil.class.getResourceAsStream("/shiyan6/jdbc.properties"); Properties prop = new Properties(); prop.load(inStream); USERNAME = prop.getProperty("jdbc.username"); PASSWORD = prop.getProperty("jdbc.password"); DRIVER = prop.getProperty("jdbc.driver"); URL = prop.getProperty("jdbc.url"); } catch (Exception e) { throw new RuntimeException("讀取資料庫配置文件異常!", e); } } /** * 獲取連接 * @return */ public static Connection getConn() { try { Class.forName(DRIVER); connection = DriverManager.getConnection(URL, USERNAME, PASSWORD); return connection; } catch (Exception e) { e.printStackTrace(); } return null; } }View Code
使用JUnit生成一個測試類,JdbcUtilTest.java,在mysql啟動的狀態下,看看能否獲取到鏈接。
package shiyan6.test; import java.sql.Connection; import org.junit.Assert; import org.junit.Test; import shiyan6.util.JdbcUtil; public class JdbcUtilTest { @Test public void testGetConn() { Connection connection = JdbcUtil.getConn(); Assert.assertNotNull(connection); System.out.println(connection); } }View Code
看到如下效果,則說明測試通過,同時控制台列印消息。
- Dao層,對資料庫的操作
涉及到的sql語句:
查找:SELECT 列名, .... FROM 表名, .... [WHERE 條件] [UNION .....] [GROUP BY .....]
[HAVING ....] [ORDER BY 排序條件];
插入:INSERT INTO 表名 [(列名, .......)] VALUES(值, ......);
更新:UPDATE 表名 SET 需修改的列=值 [WHERE .....];
刪除:DELETE FROM 表名 [WHERE ......];
- 對用戶的操作
userDao介面
package shiyan6.dao; import java.util.List; import shiyan6.entity.User; /** * UserDao 介面 * @author Changsheng * */ public interface UserDao { /** * 查詢所有普通用戶信息 * @return */ List<User> findAll(); /** * 通過用戶名查看用戶是否存在 * @param name * @return */ int findCountByName(String name); /** * 通過用戶名查看用戶 * @param name * @return */ List<User> findByName(String name); /** * 通過用戶id查詢信息 * @param id * @return */ User findById(String id); /** * 通過登錄名和密碼查詢用戶 * @param name * @param password * @return */ User findByNameAndPass(String name, String password); /** * 添加用戶 * @param user * @return */ boolean addUser(User user); /** * 修改用戶信息 * @param user * @return */ boolean editUser(User user); /** * 刪除用戶 * @param id * @return */ boolean deleteUser(String id); }View Code
userDaoImpl介面實現類
package shiyan6.dao; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; import shiyan6.entity.User; import shiyan6.util.JdbcUtil; /** * UserDao的實現類 * */ public class UserDaoImpl implements UserDao { // 獲取資料庫連接 private Connection connection = null; // prestatement用來執行動態sql語句,比statement要好 private PreparedStatement pst = null; // ResultSet 用來存放結果 private ResultSet rs = null; @Override public List<User> findAll() { // sql語句 String sql = "SELECT * FROM user WHERE role = 1 ORDER BY orderby"; // 用來存儲結果 List<User> users = new ArrayList<>(); try { connection = JdbcUtil.getConn(); pst = connection.prepareStatement(sql); rs = pst.executeQuery(); // 執行sql // 把查詢到信息給封裝到User實體類中,再放到list中 while (rs.next()) { User user = new User(); user.setId(rs.getString("id")); user.setName(rs.getString("name")); user.setPassword(rs.getString("password")); user.setRole(rs.getInt("role")); users.add(user); } } catch (Exception e) { e.printStackTrace(); } finally { // 關閉連接 try { rs.close(); pst.close(); connection.close(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } return users; } public int findCountByName(String name) { int count = 0; // sql語句,?號相當於占位符 String sql = "SELECT COUNT(*) as count FROM user WHERE name = ?"; // 存放結果 try { connection = JdbcUtil.getConn(); pst = connection.prepareStatement(sql); pst.setString(1, name); // 填充參數 rs = pst.executeQuery(); if (rs.next()) { count = rs.getInt("count"); System.out.println("count" + count); } } catch (Exception e) { e.printStackTrace(); } finally { // 關閉連接 try { rs.close(); pst.close(); connection.close(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } return count; } @Override public User findById(String id) { // sql語句,?號相當於占位符 String sql = "SELECT * FROM user WHERE id = ?"; // 存放結果 User user = null; try { connection = JdbcUtil.getConn(); pst = connection.prepareStatement(sql); pst.setString(1, id); // 填充參數 rs = pst.executeQuery(); if (rs.next()) { // 初始化User對象 user = new User(); user.setId(rs.getString("id")); user.setName(rs.getString("name")); user.setPassword(rs.getString("password")); user.setRole(rs.getInt("role")); } } catch (Exception e) { e.printStackTrace(); } finally { // 關閉連接 try { rs.close(); pst.close(); connection.close(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } return user; } @Override public User findByNameAndPass(String name, String password) { // sql語句,?號相當於占位符 String sql = "SELECT * FROM user WHERE name = ? AND password = ?"; // 存放結果 User user = null; try { connection = JdbcUtil.getConn(); pst = connection.prepareStatement(sql); pst.setString(1, name); // 填充參數 pst.setString(2, password); rs = pst.executeQuery(); if (rs.next()) { // 初始化User對象 user = new User(); user.setId(rs.getString("id")); user.setName(rs.getString("name")); user.setPassword(rs.getString("password")); user.setRole(rs.getInt("role")); } } catch (Exception e) { e.printStackTrace(); } finally { // 關閉連接 try { rs.close(); pst.close(); connection.close(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } return user; } @Override public boolean addUser(User user) { // sql語句,?號相當於占位符 String sql = "INSERT INTO user(id, name, password, role) VALUES(?,?,?,?)"; // 是否成功 boolean flag = false; try { connection = JdbcUtil.getConn(); pst = connection.prepareStatement(sql); pst.setString(1, user.getId()); // 填充參數 pst.setString(2, user.getName()); pst.setString(3, user.getPassword()); pst.setInt(4, user.getRole()); if (pst.executeUpdate() == 1) { flag = true; } } catch (Exception e) { e.printStackTrace(); } finally { // 關閉連接 try { pst.close(); connection.close(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } return flag; } @Override public boolean editUser(User user) { // sql語句,?號相當於占位符 String sql = "UPDATE user SET name=?, password=?, role=? " + "WHERE id=? "; // 是否成功 boolean flag = false; try { connection = JdbcUtil.getConn(); pst = connection.prepareStatement(sql); pst.setString(1, user.getName()); pst.setString(2, user.getPassword()); pst.setInt(3, user.getRole()); pst.setString(4, user.getId()); // 填充參數 if (pst.executeUpdate() == 1) { flag = true; } } catch (Exception e) { e.printStackTrace(); } finally { // 關閉連接 try { pst.close(); connection.close(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } return flag; } @Override public boolean deleteUser(String id) { // sql語句,?號相當於占位符 String sql = "DELETE FROM user WHERE id=?"; // 是否成功 boolean flag = false; try { connection = JdbcUtil.getConn(); pst = connection.prepareStatement(sql); pst.setString(1, id); if (pst.executeUpdate() == 1) { flag = true; } } catch (Exception e) { e.printStackTrace(); } finally { // 關閉連接 try { pst.close(); connection.close(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } return flag; } @Override public List<User> findByName(String name) { // sql語句 String sql = "SELECT * FROM user WHERE role = 1 AND name LIKE concat('%',?,'%') ORDER BY orderby"; // 用來存放結果 List<User> users = new ArrayList<>(); try { connection = JdbcUtil.getConn(); pst = connection.prepareStatement(sql); // 添加參數的值 pst.setString(1, name); rs = pst.executeQuery(); while (rs.next()) { User user = new User(); user.setId(rs.getString("id")); user.setName(rs.getString("name")); user.setPassword(rs.getString("password")); user.setRole(rs.getInt("role")); users.add(user); } } catch (Exception e) { e.printStackTrace(); } finally { try { rs.close(); pst.close(); connection.close(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } return users; } }View Code
2. 對歌曲的操作
SongDao 介面
package shiyan6.dao; import java.util.List; import shiyan6.entity.Song; /** * 對歌曲信息進行 * */ public interface SongDao { /** * 顯示所有歌曲 * @return */ List<Song> findAll(); /** * 通過id查找信息 * @return */ Song findById(String id); /** * 按條件歌曲名查詢歌曲 * @param condition * @return */ List<Song> findByName(String name); /** * 按語言查詢歌曲 * @param language * @return */ List<Song> findBylanguage(String language); /** * 根據歌手來查詢歌曲 * @param singer * @return */ List<Song> findBySinger(String singer); /** * 格局歌曲類別來查詢歌曲 * @param category * @return */ List<Song> findByCategory(String category); /** * 刪除歌曲 * @param id * @return */ boolean deletSong(String id); /** * 添加歌曲 * @param song * @return */ boolean addSong(Song song); /** * 修改歌曲 * @param song * @return */ boolean updateSong(Song song); }View Code
SongDaoImpl實現類
package shiyan6.dao; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; import shiyan6.entity.Song; import shiyan6.util.JdbcUtil; public class SongDaoImpl implements SongDao { // 獲取資料庫連接 private Connection connection = null; // prestatement用來執行動態sql語句,比statement要好 private PreparedStatement pst = null; // ResultSet 用來存放結果 private ResultSet rs = null; @Override public List<Song> findAll() { // sql語句 String sql = "SELECT * FROM song ORDER BY orderby"; // 用來存放結果 List<Song> songs = new ArrayList<>(); try { connection = JdbcUtil.getConn(); pst = connection.prepareStatement(sql); rs = pst.executeQuery(); while (rs.next()) { Song song = new Song(); song.setId(rs.getString("id")); song.setName(rs.getString("name")); song.setLanguage(rs.getString("language")); song.setCategory(rs.getString("category")); song.setSinger(rs.getString("singer")); songs.add(song); } } catch (Exception e) { e.printStackTrace(); } finally { try { rs.close(); pst.close(); connection.close(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } return songs; } public Song findById(String id) { // sql語句 String sql = "SELECT * FROM song WHERE id = ? ORDER BY orderby"; // 用來存放結果 try { connection = JdbcUtil.getConn(); pst = connection.prepareStatement(sql); // 添加參數的值 pst.setString(1, id); rs = pst.executeQuery(); if (rs.next()) { Song song = new Song(); song.setId(rs.getString("id")); song.setName(rs.getString("name")); song.setLanguage(rs.getString("language")); song.setCategory(rs.getString("category")); song.setSinger(rs.getString("singer")); return song; } } catch (Exception e) { e.printStackTrace(); } finally { try { rs.close(); pst.close(); connection.close(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } return null; } @Override public List<Song> findByName(String name) { // sql語句 String sql = "SELECT * FROM song WHERE name LIKE concat('%',?,'%') ORDER BY orderby"; // 用來存放結果 List<Song> songs = new ArrayList<>(); try { connection = JdbcUtil.getConn(); pst = connection.prepareStatement(sql); // 添加參數的值 pst.setString(1, name); rs = pst.executeQuery(); while (rs.next()) { Song song = new Song(); song.setId(rs.getString("id")); song.setName(rs.getString("name")); song.setLanguage(rs.getString("language")); song.setCategory(rs.getString("category")); song.setSinger(rs.getString("singer")); songs.add(song); } } catch (Exception e) { e.printStackTrace(); } finally { try { rs.close(); pst.close(); connection.close(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } return songs; } @Override public List<Song> findBylanguage(String language) { // sql語句 String sql = "SELECT * FROM song WHERE language LIKE concat('%',?,'%') ORDER BY orderby"; // 用來存放結果 List<Song> songs = new ArrayList<>(); try { connection = JdbcUtil.getConn(); pst = connection.prepareStatement(sql); // 添加參數的值 pst.setString(1, language); rs = pst.executeQuery(); while (rs.next()) { Song song = new Song(); song.setId(rs.getString("id")); song.setName(rs.getString("name")); song.setLanguage(rs.getString("language")); song.setCategory(rs.getString("category")); song.setSinger(rs.getString("singer")); songs.add(song); } } catch (Exception e) { e.printStackTrace(); } finally { try { rs.close(); pst.close(); connection.close(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } return songs; } @Override public List<Song> findBySinger(String singer) { // sql語句 String sql = "SELECT * FROM song WHERE singer LIKE concat('%',?,'%') ORDER BY orderby"; // 用來存放結果 List<Song> songs = new ArrayList<>(); try { connection = JdbcUtil.getConn(); pst = connection.prepareStatement(sql); // 添加參數的值 pst.setString(1, singer); rs = pst.executeQuery(); while (rs.next()) { Song song = new Song(); song.setId(rs.getString("id")); song.setName(rs.getString("name")); song.setLanguage(rs.getString("language")); song.setCategory(rs.getString("category")); song.setSinger(rs.getString("singer")); songs.add(song); } } catch (Exception e) { e.printStackTrace(); } finally { try { rs.close(); pst.close(); connection.close(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } return songs; } @Override public List<Song> findByCategory(String category) { // sql語句 String sql = "SELECT * FROM song WHERE category LIKE concat('%',?,'%') ORDER BY orderby"; // 用來存放結果 List<Song> songs = new ArrayList<>(); try { connection = JdbcUtil.getConn(); pst = connection.prepareStatement(sql); // 添加參數的值 pst.setString(1, category); rs = pst.executeQuery(); while (rs.next()) { Song song = new Song();