자바 기초 개발 의 JDBC 조작 데이터베이스 첨삭 검사,페이지 별 조회 실례 상세 설명
첨삭 검사 조작
페이지 조회 조작
1.검색 결 과 를 list 로 되 돌려 줍 니 다.
2.검색 결 과 를 jsonArray 로 되 돌려 줍 니 다.
3.총 기록 항목 수 조회
우선 관련 설정 정 보 를 살 펴 보 겠 습 니 다.
public static final String USER_NAME = "root";
public static final String PWD = "123456789";
public static final String DRIVER = "com.mysql.jdbc.Driver";
public static final String URL = "jdbc:mysql://localhost:3306/web_demon";
/** */
public static final int PAGE_SIZE_DEFAULT = 10;
첨삭 조작데이터베이스 연결 대상 가 져 오기
/**
*
* @return
*/
public Connection getConnection(Connection conn) {
if(conn == null){
try {
Class.forName(Config.DRIVER);
conn = DriverManager.getConnection(Config.URL, Config.USER_NAME, Config.PWD);
} catch (Exception e) {
e.printStackTrace();
}
}
return conn;
}
패 키 징 추가 삭제 작업
/**
* , ,
* @param sql sql
* : "insert into user (name,sex) values (?,?)";
* "delete from user where id=?";
* "update user set name=?,sex=? where id=? and sex=?";
* @param values
* @return ,-1
*/
private int execute(String sql,Object... values){
Connection conn = null;
PreparedStatement pStmt = null;
try {
conn = this.getConnection(conn);
pStmt = conn.prepareStatement(sql);
//
if(pStmt != null && values != null && values.length > 0){
for (int i = 0; i < values.length; i++) {
pStmt.setObject(i+1, values[i]);
}
}
int i =pStmt.executeUpdate();
return i;
} catch (Exception e) {
e.printStackTrace();
} finally {
if (conn != null) {
this.closeConnection(conn);
}
}
return -1;
}
호출 방법
//
public static void insert(){
String sql = "insert into user (name,sex) values (?,?)";
Object[] values = new Object[]{" ",0};
int res = baseImp.execute(sql, values);
System.out.println("insert res="+res);
}
//
public static void delete(){
String sql = "delete from user where id=?";
Object[] values = new Object[]{2};
int res = baseImp.execute(sql, values);
System.out.println("delete res="+res);
}
//
public static void update(){
String sql = "update user set name=?,sex=? where id=? and sex=?";
Object[] values = new Object[]{" ",1,1,0};
int res = baseImp.execute(sql, values);
System.out.println("update res="+res);
}
조회 조작1.검색 결 과 를 list 로 되 돌려 줍 니 다.
/**
* list
* @param pageIndex
* @param pageSize
* @param attachTableName key , :user.id, id
* @param sql :"select u.id,u.name,u.sex,u.depart_id AS departId,d.* from user u,depart d where u.depart_id=d.id"
* @param values
* @throws SQLException
*/
private List<Map<String, Object>> queryList(int pageIndex,int pageSize,boolean attachTableName,String sql,Object... values) throws SQLException{
Connection conn = null;
PreparedStatement pStmt = null;
List<Map<String, Object>> dataList = null;
//
if(pageIndex <= 0){
pageIndex = 1;
}
if(pageSize <= 0){
pageSize = Config.PAGE_SIZE_DEFAULT;
}
conn = this.getConnection(conn);
pStmt = conn.prepareStatement(sql);
//
if(pStmt != null && values != null && values.length > 0){
for (int i = 0; i < values.length; i++) {
pStmt.setObject(i+1, values[i]);
}
}
//
pStmt.setMaxRows(pageIndex*pageSize);
ResultSet rs = pStmt.executeQuery();
//
rs.relative((pageIndex-1)*pageSize);
if(rs != null){
try {
dataList = new ArrayList<Map<String,Object>>();
ResultSetMetaData md = rs.getMetaData(); // (rs) , 、
//
while(rs.next()){
Map<String, Object> map = new LinkedHashMap();
for (int i = 1; i <= md.getColumnCount(); i++) {
map.put(attachTableName?(formatTableName(md.getTableName(i))+"."+md.getColumnLabel(i)):(md.getColumnLabel(i)), rs.getObject(i));
}
dataList.add(map);
}
}finally{
if(rs != null){
rs.close();
}
if(pStmt != null){
pStmt.close();
}
if (conn != null) {
this.closeConnection(conn);
}
}
}
return dataList;
}
호출 목록 조회
public static void queryList(){
String sql = "select u.*,d.* from user u,depart d where u.depart_id=d.id";
try {
List<Map<String, Object>> dataList = baseImp.queryForListAttachTableName(2,2,sql, null);
// List<Map<String, Object>> dataList = baseImp.queryForList(2,2,sql, null);
for (Map<String, Object> map : dataList) {
for (String key : map.keySet()) {
System.out.print(key+"="+map.get(key)+" ");
}
System.out.println();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
결실![](https://s1.md5.ltd/image/55bb78662512562a24748883b0025af7.png)
2.검색 결 과 를 jsonArray 로 되 돌려 줍 니 다.
/**
* ArrayList
* @param key , :user.id, id
* @param sql :"select u.id,u.name,u.sex,u.depart_id AS departId,d.* from user u,depart d where u.depart_id=d.id"
* @param values
* @throws SQLException
*/
private JSONArray queryJsonArray(int pageIndex,int pageSize,boolean attachTableName,String sql,Object... values) throws SQLException{
JSONArray jsonArray = null;
Connection conn = null;
PreparedStatement pStmt = null;
//
if(pageIndex <= 0){
pageIndex = 1;
}
if(pageSize <= 0){
pageSize = Config.PAGE_SIZE_DEFAULT;
}
conn = this.getConnection(conn);
pStmt = conn.prepareStatement(sql);
//
if(pStmt != null && values != null && values.length > 0){
for (int i = 0; i < values.length; i++) {
pStmt.setObject(i+1, values[i]);
}
}
//
pStmt.setMaxRows(pageIndex*pageSize);
ResultSet rs = pStmt.executeQuery();
//
rs.relative((pageIndex-1)*pageSize);
if(rs != null){
try {
jsonArray = new JSONArray();
ResultSetMetaData md = rs.getMetaData(); // (rs) , 、
//
while(rs.next()){
JSONObject jsonObject = new JSONObject();
for (int i = 1; i <= md.getColumnCount(); i++) {
jsonObject.put(attachTableName?(formatTableName(md.getTableName(i))+"."+md.getColumnLabel(i)):(md.getColumnLabel(i)), rs.getObject(i)+"");
}
jsonArray.add(jsonObject);
}
}finally{
if(rs != null){
rs.close();
}
if(pStmt != null){
pStmt.close();
}
if (conn != null) {
this.closeConnection(conn);
}
}
}
return jsonArray;
}
jsonArray 조회 호출
public static void queryJsonArray(){
// String sql = "select * from user u";
String sql = "select u.*,d.* from user u,depart d where u.depart_id=d.id";
// String sql = "select u.id AS uid,u.name,u.sex,u.depart_id AS departId,d.name from user u,depart d where u.depart_id=d.id";
// String sql = "select u.id,u.name,u.sex,u.depart_id AS departId,d.* from user u,depart d where u.depart_id=d.id";
try {
JSONArray jsonArray = baseImp.queryForJsonArrayAttachTableName(2,2,sql, null);
// JSONArray jsonArray = baseImp.queryForJsonArray(sql, null);
System.out.println(jsonArray.toString());
for (int i = 0; i < jsonArray.size(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
Iterator<?> iterator = jsonObject.keys();
Object key = null;
while (iterator.hasNext()) {
key = iterator.next();
System.out.print(key+" "+jsonObject.get(key)+" ");
}
System.out.println();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
결실![](https://s1.md5.ltd/image/c00b3a847121292012f95ecf7acedc81.png)
[{"user.id":"4","user.name":" ","user.sex":"0","user.depart_id":"3","depart.id":"3","depart.name":" ","depart.desc":" "},{"user.id":"5","user.name":" ","user.sex":"1","user.depart_id":"1","depart.id":"1","depart.name":" ","depart.desc":" "}]
user.id 4 user.name user.sex 0 user.depart_id 3 depart.id 3 depart.name depart.desc
user.id 5 user.name user.sex 1 user.depart_id 1 depart.id 1 depart.name depart.desc
3.총 기록 항목 수 조회
/**
*
* @param sql :"select count(*) from user where xxx"
* @param values
* @throws SQLException
*/
public int queryCount(String sql,Object... values) throws SQLException{
int count = -1;
Connection conn = null;
PreparedStatement pStmt = null;
conn = this.getConnection(conn);
pStmt = conn.prepareStatement(sql);
//
if(pStmt != null && values != null && values.length > 0){
for (int i = 0; i < values.length; i++) {
pStmt.setObject(i+1, values[i]);
}
}
ResultSet rs = pStmt.executeQuery();
if(rs != null){
try {
while(rs.next()){
count = rs.getInt(1);
}
}finally{
if(rs != null){
rs.close();
}
if(pStmt != null){
pStmt.close();
}
if (conn != null) {
this.closeConnection(conn);
}
}
}
return count;
}
호출 조회 총 기록 항목 수
public static void queryCount(){
String sql = "select count(*) from user u";
try {
System.out.println("count="+baseImp.queryCount(sql, null));
} catch (SQLException e) {
e.printStackTrace();
}
}
결실![](https://s1.md5.ltd/image/dd63208dea99482c2f1379146dc7cddb.png)
이로써 자바 기초 개발 에서 JDBC 가 데이터 베 이 스 를 추가 삭제 하고 수정 하 는 작업 과 페이지 별 조 회 를 소 개 했 습 니 다.이 방면 에 관 한 글 을 더 알 고 싶다 면 아래 의 관련 링크 를 보 세 요.
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
JPA + QueryDSL 계층형 댓글, 대댓글 구현(2)이번엔 전편에 이어서 계층형 댓글, 대댓글을 다시 리팩토링해볼 예정이다. 이전 게시글에서는 계층형 댓글, 대댓글을 구현은 되었지만 N+1 문제가 있었다. 이번에는 그 N+1 문제를 해결해 볼 것이다. 위의 로직은 이...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.