package test;
import java.sql.ResultSet;
import java.sql.SQLException;
import org.junit.Test;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
public class TestJDBC {
JdbcTemplate template;
public void upload(){
//设置数据库信息
DriverManagerDataSource source = new DriverManagerDataSource();
source.setDriverClassName("com.mysql.jdbc.Driver");
source.setUrl("jdbc:mysql://localhost:3306/my?useUnicode=true&characterEncoding=UTF-8");
source.setUsername("root");
source.setPassword("123456");
//创建JDBCTemplate对象,设置数据源
template = new JdbcTemplate(source);
}
@Test//添加操作
public void add(){
upload();
//调用JDBCTemplate对象里面的方法实现操作
String sql = "insert into grade value(?,?,?)";//创建SQL语句
int row = template.update(sql,5,"","数据库操作");
System.out.println(row);
}
@Test
//更新操作
public void update(){
upload();
String sql = "update grade set GNAME=? where GID=?";
int row = template.update(t-user,"",5);
System.out.println(row);
}
@Test//删除操作
public void delete(){
upload();
String sql = "delete from grade where GID=?";
int row = template.update(t-user,5);
System.out.println(row);
}
@Test//获取表中数据个数操作
public void count(){
upload();
String sql = "select count(*) from grade";
int row = template.queryForObject(t-user, Integer.class);
System.out.println(row);
}
@Test
public void getObject(){
upload();
String sql = "select * from grade where gid=?";
Grade grade = template.queryForObject(t-user, new MyRowMapper(), 4);
System.out.println(grade);
}
}
class MyRowMapper implements RowMapper
@Override
public Grade mapRow(ResultSet arg0, int arg1) throws SQLException {
Grade grade = new Grade();
grade.setgName(arg0.getString("GName"));
grade.setgDesc(arg0.getString("GDesc"));
return grade;
}
}