用idea新建一个Java文件music
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/e2e1f7171586fe65cff96271fa54cb51.png)
新建两个MySQL数据库music音乐管理数据库与tb_user用户数据库
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/b68d16e6cb30e224fdc0388af9fa1633.png)
MusicDao代码如下
package com.zhongruan.dao;
import com.zhongruan.model.Music;
import com.zhongruan.util.DBUtil;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
public class MusicDao {
public List<Music> findMusics() {
ResultSet resultSet = null;
PreparedStatement statement = null;
Connection connection = null;
List<Music> musics = new ArrayList<>();
try {
connection = DBUtil.getConnection();
//3.写sql
String sql = "select * from music";
//4.得到statement对象
statement = connection.prepareStatement(sql);
//5.执行sql
resultSet = statement.executeQuery();
//6.处理结果集
while (resultSet.next()) {
Music music = new Music();
music.setId(resultSet.getInt(1));
music.setName(resultSet.getString(2));
music.setAuthor(resultSet.getString(3));
musics.add(music);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
//7.关闭资源
DBUtil.closeAll(resultSet, statement, connection);
}
return musics;
}
public void delete(int id) throws SQLException, ClassNotFoundException {
Connection connection = DBUtil.getConnection();
String sql = "delete from music where id=?";
PreparedStatement statement = connection.prepareStatement(sql);
statement.setInt(1,id);
statement.executeUpdate();
DBUtil.closeAll(null,statement,connection);
}
public void charu(String name,String author){
ResultSet resultSet=null;
PreparedStatement statement=null;
Connection connection=null;
try {
connection = DBUtil.getConnection();
String sql = "insert into music(name,author)values(?,?))";
statement = connection.prepareStatement(sql);
statement.setString(1, name);
statement.setString(2,author);
statement.executeUpdate();
}catch (Exception e){
e.printStackTrace();
}finally {
DBUtil.closeAll(resultSet,statement,connection);
}
}
public static void xiugai(int id,String newname,String author)throws SQLException,ClassNotFoundException{
Connection connection=DBUtil.getConnection();
String sql="update music set name=?,author=?where id=?";
PreparedStatement statement=connection.prepareStatement(sql);
statement.setString(1,newname);
statement.setStri