首先需要创建一个数据库jdbc:mysql://localhost:3306/homework我命名为homework在homework数据库中创建score表,表中数据自行添加。
然后就是BaseDao,连接数据库的类,还有关闭数据库连接的方法
public class BaseDao {
private static final String DRIVER = "com.mysql.jdbc.Driver";
private static final String URL = "jdbc:mysql://localhost:3306/homework";
private static final String USER = "root";
private static final String PWD = "数据库密码";
static{
try {
Class.forName(DRIVER);
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
public Connection getConn() {
Connection conn = null;
try {
conn = DriverManager.getConnection(URL,USER,PWD);
} catch (SQLException e) {
e.printStackTrace();
}
return conn;
}
public void close(ResultSet rs,Statement state,Connection conn) {
try {
if(rs != null) {
rs.close();
}
if(state != null) {
state.close();
}
if(conn !=null) {
conn.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
还有就是POJO类存放score的数据
public class Score {
private int id;
private String name;
private String course;
private int degree;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getCourse() {
return course;
}
public void setCourse(String course) {
this.course = course;
}
public int getDegree() {
return degree;
}
public void setDegree(int degree) {
this.degree = degree;
}
}
还有ScoreDao类,用于实现增删改查的方法
public class ScoreDao {
//实现增删改查的方法
BaseDao bd = new BaseDao();
List<Score> list1 = new ArrayList<Score>();
Connection conn = null;
Statement state = null;
ResultSet rs = null;
PreparedStatement pstate;
String [] str = new String[4];
//将数据库数据导出
public List<Score> ScoreDao() {
conn = bd.getConn();
try {
state = conn.createStatement();
} catch (SQLException e) {
e.printStackTrace();
}
String sql = "select * from score";
try {
rs = state.executeQuery(sql);
} catch (SQLException e) {
e.printStackTrace();
}
try {
while(rs.next()) {
Score stu = new Score();
stu.setId(rs.getInt("id"));
stu.setName(rs.getString("name"));
stu.setCourse(rs.getString("course"));
stu.setDegree(rs.getInt("degree"));
list1.add(stu);
}
bd.close(rs, pstate, conn);
} catch (SQLException e) {
e.printStackTrace();
}
return list1;
}
//添加数据入库
@SuppressWarnings("finally")
public String Insert(String id,String name ,String course,String degree) {
conn = bd.getConn();
int result = -1;
String sql = "insert into score values("+id+",'"