基于java的音乐管理系统数据库java代码
时间: 2023-08-23 12:03:41 浏览: 43
以下是一个简单的基于Java的音乐管理系统数据库代码示例,你可以根据自己的需求进行修改和扩展:
```
import java.sql.*;
public class MusicDB {
private Connection connection;
public MusicDB() {
try {
Class.forName("com.mysql.jdbc.Driver");
connection = DriverManager.getConnection("jdbc:mysql://localhost/music", "root", "");
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
}
public void addSong(String name, String artist, int year) {
try {
PreparedStatement statement = connection.prepareStatement("INSERT INTO songs (name, artist, year) VALUES (?, ?, ?)");
statement.setString(1, name);
statement.setString(2, artist);
statement.setInt(3, year);
statement.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
}
}
public void deleteSong(int id) {
try {
PreparedStatement statement = connection.prepareStatement("DELETE FROM songs WHERE id = ?");
statement.setInt(1, id);
statement.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
}
}
public void updateSong(int id, String name, String artist, int year) {
try {
PreparedStatement statement = connection.prepareStatement("UPDATE songs SET name = ?, artist = ?, year = ? WHERE id = ?");
statement.setString(1, name);
statement.setString(2, artist);
statement.setInt(3, year);
statement.setInt(4, id);
statement.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
}
}
public ResultSet getSong(int id) {
ResultSet result = null;
try {
PreparedStatement statement = connection.prepareStatement("SELECT * FROM songs WHERE id = ?");
statement.setInt(1, id);
result = statement.executeQuery();
} catch (SQLException e) {
e.printStackTrace();
}
return result;
}
public ResultSet getAllSongs() {
ResultSet result = null;
try {
PreparedStatement statement = connection.prepareStatement("SELECT * FROM songs");
result = statement.executeQuery();
} catch (SQLException e) {
e.printStackTrace();
}
return result;
}
public void closeConnection() {
try {
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
```
此示例使用了MySQL数据库,并提供了添加、删除、更新、查询单个和查询所有歌曲的方法。你可以根据需要对其进行修改和扩展。