发表于: 2018-03-26 20:17:08
1 380
一、今天完成的事情
JDBC实现对数据库的增删查改
(1)用了四个类来实现功能,首先是实体类
将域设为私有成员,并使用get方法和set方法实现访问和修改。
(2)JdbcUtil类主要负责注册驱动,创建数据库连接并返回
public class JdbcUtil {
private static final String URL="jdbc:mysql://127.0.0.1:3306/java";
private static final String USER="root";
private static final String PASSWORD="123456";
private static Connection conn = null;
static {
try {
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection(URL,USER,PASSWORD);
} catch (Exception e) {
e.printStackTrace();
}
}
public static Connection getConnection(){
return conn;
}
}
(3)JdbcDao类负责对数据库增删查改的具体方法实现。
public class JdbcDao {
public void add(User user) throws SQLException{
Connection connection = JdbcUtil.getConnection();
String sql = "INSERT INTO sign_up(name,qq,city,type,enterTime,school,idOnline,reportLink,wish,knowFromWhere,consellor,createAt,updateAt)"+
"VALUES (?,?,?,?,?,?,?,?,?,?,?,CURRENT_DATE ,CURRENT_DATE )";
PreparedStatement pstm = connection.prepareStatement(sql);
pstm.setString(1,user.getName());
pstm.setString(2,user.getQq());
pstm.setString(3,user.getCity());
pstm.setString(4,user.getType());
pstm.setString(5,user.getEnterTime());
pstm.setString(6,user.getSchool());
pstm.setString(7,user.getIdOnline());
pstm.setString(8,user.getReportLink());
pstm.setString(9,user.getWish());
pstm.setString(10,user.getKnowFromWhere());
pstm.setString(11,user.getConsellor());
pstm.execute();
pstm.close();
connection.close();
// System.out.println("插入成功!");
}
public void delete(Integer id) throws SQLException{
Connection connection = JdbcUtil.getConnection();
String sql = "DELETE FROM sign_up WHERE id=?";
PreparedStatement psmt = connection.prepareStatement(sql);
psmt.setInt(1,id);
psmt.execute();
psmt.close();
connection.close();
}
public void update(User user) throws SQLException{
Connection connection = JdbcUtil.getConnection();
String sql="UPDATE sign_up SET name=?,qq=?,updateAt=current_date() WHERE id=?";
PreparedStatement psmt = connection.prepareStatement(sql);
psmt.setString(1,user.getName());
psmt.setString(2,user.getQq());
psmt.setInt(3,user.getId());
psmt.close();
connection.close();
}
public List<User> query() throws SQLException{
Connection connection = JdbcUtil.getConnection();
String sql="SELECT name,qq FROM sign_up";
Statement stmt = connection.createStatement();
ResultSet resultSet = stmt.executeQuery(sql);
List<User> list = new ArrayList<User>();
User user = null;
while (resultSet.next()) {
user = new User();
user.setName(resultSet.getString("name"));
user.setQq(resultSet.getString("qq"));
list.add(user);
}
return list;
}
}
(4)JdbcAction类实现具体的方法的调用。
由于今天白天有课,所以对于JdbcTemplate和mybatis还没有去了解。留着明天的任务。
二、明天计划的事情
熟悉掌握JdbcTemplate对数据库的操作的方法,时间充裕可以了解mybatis。
评论