jdbc08
JDBC31Servlet
sql 에서 테이블 만들고, servlet 실행해서 값 넣기
doGet
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// 0.
ServletContext application = request.getServletContext();
DataSource ds = (DataSource) application.getAttribute("dbpool");
String sql = "INSERT INTO mytable10 (col1, col2, col3, col4, col5, col6, col7) VALUES (?, ?, ?, ?, ?, ?, ?)";
try (Connection con = ds.getConnection();
PreparedStatement pstmt = con.prepareStatement(sql)) {
pstmt.setInt(1, 9999999); // INT
pstmt.setDouble(2, 3.14); // DOUBLE
pstmt.setDouble(3, 1234567.1234); // DEC(10 , 3 )
pstmt.setString(4, "ABC"); // CHAR(3)
pstmt.setString(5, "Hello World"); // VARCHAR(255)
pstmt.setDate(6, java.sql.Date.valueOf("2021-11-26")); // DATE
pstmt.setTimestamp(7, java.sql.Timestamp.valueOf("2021-11-26 09:33:12")); // DATETIME
pstmt.executeQuery();
} catch (Exception e) {
e.printStackTrace();
}
}
12sample-jdbc31.sql
CREATE TABLE mytable10 (
col1 int,
col2 double,
col3 DEC(10, 3),
col4 CHAR(3),
col5 VARCHAR(255),
col6 DATE,
col7 DATETIME
);
서블릿에서 sql 코드 insert 할 컬럼 값들을 ? 로 작성
try에서 pstmt.setDatatype 으로 ? 에 들어갈 값 넣기 (지금은 서블릿으로 직접)
servlet 실행 전
servlet 실행 후
JDBC32Servlet
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// 0.
ServletContext application = request.getServletContext();
DataSource ds = (DataSource) application.getAttribute("dbpool");
String sql = "SELECT col1, col2, col3, col4, col5, col6, col7 FROM mytable10";
try (Connection con = ds.getConnection();
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery(sql);) {
while (rs.next()) {
// int col1 = rs.getInt("col1"); // INT
Integer col1 = rs.getInt("col1"); // INT
// double col2 = rs.getDouble("col2"); // DOUBLE
Double col2 = rs.getDouble("col2"); // DOUBLE
// double col3 = rs.getDouble("col3"); // DEC(10, 3)
Double col3 = rs.getDouble("col3"); // DEC(10, 3)
String col4 = rs.getString("col4"); // CHAR(3)
String col5 = rs.getString("col5"); // VARCHAR(255)
java.sql.Date col6 = rs.getDate("col6"); // DATE
java.sql.Timestamp col7 = rs.getTimestamp("col7"); // DATETIME
System.out.println(col1 + ", " + col2 + ", " + col3 + ", " + col4 + ", " + col5 + ", " + col6 + ", " + col7);
}
} catch (Exception e) {
e.printStackTrace();
}
}
select 로 31에서 넣었던 컬럼 값들을 조회하기
sql 코드로 select 하는 코드 작성
rs.getDatatype("컬럼명") 은 해당 컬럼의 값을 반환하는 것
그래서 값들을 변수에 저장한 다음 아래 System.out.println 으로 출력 - 콘솔창에 출력됨
* java 에서의 DATE, DATETIME
- set/get+Date - java.sql.Date - java.sql.Date.valueOf("") - java.time.LocalDate
- set/get+Timestamp - java.sql.Timestamp - java.sql.Timestamp.valueOf("") - java.time.LocalDateTime
java.time.LocalDate date; // Local Date
java.time.LocalDateTime dateTime; // LocalDateTime
java.sql.Date col6 = rs.getDate("col6"); // DATE
java.sql.Timestamp col7 = rs.getTimestamp("col7"); // DATETIME
java.time.LocalDate date = col6.toLocalDate(); // Local Date
java.time.LocalDateTime dateTime = col7.toLocalDateTime(); // LocalDateTime
System.out.println(col6 + ", " + col7);
System.out.println(date + ", " + dateTime);
JDBC33Servlet
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// 0.
ServletContext application = request.getServletContext();
DataSource ds = (DataSource) application.getAttribute("dbpool");
String sql = "SELECT col1, col2, col3, col4, col5, col6, col7 FROM mytable10";
try (Connection con = ds.getConnection();
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery(sql);) {
while (rs.next()) {
java.sql.Date col6 = rs.getDate("col6"); // DATE
java.sql.Timestamp col7 = rs.getTimestamp("col7"); // DATETIME
java.time.LocalDate date = col6.toLocalDate();
java.time.LocalDateTime dateTime = col7.toLocalDateTime();
System.out.println(col6 + ", " + col7);
System.out.println(date + ", " + dateTime);
}
} catch (Exception e) {
e.printStackTrace();
}
}
sql 코드 작성 - select 로 컬럼 값들 조회
col6, col7 만 받아서 저장하고 출력하기
한번은 java.sql.Date, java.sql.Timestamp 으로,
한번은 java.time.LocalDate, java.time.LocalDatetime 으로 출력했음
차이 ↓
JDBC34Servlet
doGet
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// 0.
ServletContext application = request.getServletContext();
DataSource ds = (DataSource) application.getAttribute("dbpool");
String sql = "INSERT INTO mytable10 (col1, col2, col3, col4, col5, col6, col7) VALUES (?, ?, ?, ?, ?, ?, ?)";
try (Connection con = ds.getConnection();
PreparedStatement pstmt = con.prepareStatement(sql)) {
pstmt.setInt(1, 9999999); // INT
pstmt.setDouble(2, 3.14); // DOUBLE
pstmt.setDouble(3, 1234567.1234); // DEC(10 , 3 )
pstmt.setString(4, "ABC"); // CHAR(3)
pstmt.setString(5, "Hello World"); // VARCHAR(255)
java.time.LocalDate date = LocalDate.parse("2021-11-26");
java.time.LocalDateTime dateTime = LocalDateTime.parse("2021-11-26T09:33:12");
pstmt.setDate(6, java.sql.Date.valueOf(date)); // DATE
pstmt.setTimestamp(7, java.sql.Timestamp.valueOf(dateTime)); // DATETIME
pstmt.executeQuery();
} catch (Exception e) {
e.printStackTrace();
}
}
31 에서 테이블에 값들을 insert 했는데,
그 코드 복붙하고 col6, col7 을 LocalDate, LocalDateTime 으로 먼저 저장한 다음 형변환해서 넣기
** LocalDateTime 으로 작성할 때는 시:분:초 앞에 T 를 작성해줘야 한다
JDBC35Servlet
화면까지 작성해보기
jdbc08
v35.jsp
<body>
<h1>mytable10 insert</h1>
<form action="" method="post">
<input type="number" value="345" name="col1"> <br>
<input type="number" step="0.1" name="col2"> <br>
<input type="number" step="0.001" name="col3"> <br>
<input type="text" maxlength="3" name="col4"> <br>
<input type="text" name="col5"> <br>
<input type="date" name="col6"> <br>
<input type="datetime-local" name="col7"> <br>
<input type="submit" value="입력">
</form>
</body>
form 으로 각 컬럼값 입력창 작성, post 방식으로 전달
type 확인하기 - number, text, date, datetime-local
name 들은 모두 col1,2,3... 으로 전달되어짐
그 외, number type 의 step, maxlength attribute 도 눈여겨볼것
JDBC35Servlet
doGet, doPost
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String path = "/WEB-INF/view/jdbc08/v35.jsp";
request.getRequestDispatcher(path).forward(request, response);
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// 0.
ServletContext application = request.getServletContext();
DataSource ds = (DataSource) application.getAttribute("dbpool");
MyTable10Dao dao = new MyTable10Dao();
boolean ok = false;
// 2.
String col1 = request.getParameter("col1");
String col2 = request.getParameter("col2");
String col3 = request.getParameter("col3");
String col4 = request.getParameter("col4");
String col5 = request.getParameter("col5");
String col6 = request.getParameter("col6");
String col7 = request.getParameter("col7");
Bean10 bean = new Bean10();
bean.setCol1(Integer.parseInt(col1));
bean.setCol2(Double.parseDouble(col2));
bean.setCol3(Double.parseDouble(col3));
bean.setCol4(col4);
bean.setCol5(col5);
bean.setCol6(LocalDate.parse(col6));
bean.setCol7(LocalDateTime.parse(col7));
// 3.
try (Connection con = ds.getConnection()) {
dao.insert(con, bean);
} catch (Exception e) {
e.printStackTrace();
}
}
doGet - v35.jsp 로 포워딩~
doPost - MyTable10Dao 객체 dao 생성, boolean ok = false
jsp 에서 전달받은 각 컬럼 값들을 문자열로 저장, Bean10 객체 bean 생성, 컬럼 값들을 bean.set 으로 저장 (일부 형변환)
try 에서 bean 을 매개변수로 전달하며 dao.insert 메소드 실행
jdbc08.bean
Bean10
package jdbc08.bean;
import java.time.LocalDate;
import java.time.LocalDateTime;
public class Bean10 {
private Integer col1;
private Double col2;
private Double col3;
private String col4;
private String col5;
private LocalDate col6;
private LocalDateTime col7;
public Integer getCol1() {
return col1;
}
public void setCol1(Integer col1) {
this.col1 = col1;
}
public Double getCol2() {
return col2;
}
public void setCol2(Double col2) {
this.col2 = col2;
}
public Double getCol3() {
return col3;
}
public void setCol3(Double col3) {
this.col3 = col3;
}
public String getCol4() {
return col4;
}
public void setCol4(String col4) {
this.col4 = col4;
}
public String getCol5() {
return col5;
}
public void setCol5(String col5) {
this.col5 = col5;
}
public LocalDate getCol6() {
return col6;
}
public void setCol6(LocalDate col6) {
this.col6 = col6;
}
public LocalDateTime getCol7() {
return col7;
}
public void setCol7(LocalDateTime col7) {
this.col7 = col7;
}
}
jdbc08.dao
MyTable10DAO
package jdbc08.dao;
import java.sql.Connection;
import java.sql.Date;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.List;
import jdbc08.bean.Bean10;
public class MyTable10Dao {
public boolean insert(Connection con, Bean10 bean) {
String sql = "INSERT INTO mytable10 (col1, col2, col3, col4, col5, col6, col7) "
+ "VALUE (?, ?, ?, ?, ?, ?, ?)";
try (PreparedStatement pstmt = con.prepareStatement(sql)) {
pstmt.setInt(1, bean.getCol1());
pstmt.setDouble(2, bean.getCol2());
pstmt.setDouble(3, bean.getCol3());
pstmt.setString(4, bean.getCol4());
pstmt.setString(5, bean.getCol5());
pstmt.setDate(6, Date.valueOf(bean.getCol6()));
pstmt.setTimestamp(7, Timestamp.valueOf(bean.getCol7()));
return pstmt.executeUpdate() == 1;
} catch (Exception e) {
e.printStackTrace();
}
return false;
}
}
public boolean insert(Connection con, Bean10 bean) 메소드
insert 하는 sql 코드 작성
각 컬럼 값은 (jsp → servlet → bean) servlet 에서 bean.set 으로 bean 에 저장했으므로 bean.get 으로 얻어옴
그리고 ? 에 넣어줌
public List<Bean10> getList(Connection con) 메소드
리스트 생성
select 로 테이블 조회하도록 sql 작성, sql 실행, 컬럼값 받아서 bean 에 저장
확인은 sql 에서 (아직 결과를 받아오는 코드는 작성하지 않았음)
JDBC36Servlet
insert 하고 그 결과까지 받아오는 코드를 작성해보자
MyTable10Dao
public class MyTable10Dao {
public boolean insert(Connection con, Bean10 bean) {
String sql = "INSERT INTO mytable10 (col1, col2, col3, col4, col5, col6, col7) "
+ "VALUE (?, ?, ?, ?, ?, ?, ?)";
try (PreparedStatement pstmt = con.prepareStatement(sql)) {
pstmt.setInt(1, bean.getCol1());
pstmt.setDouble(2, bean.getCol2());
pstmt.setDouble(3, bean.getCol3());
pstmt.setString(4, bean.getCol4());
pstmt.setString(5, bean.getCol5());
pstmt.setDate(6, Date.valueOf(bean.getCol6()));
pstmt.setTimestamp(7, Timestamp.valueOf(bean.getCol7()));
return pstmt.executeUpdate() == 1;
} catch (Exception e) {
e.printStackTrace();
}
return false;
}
public List<Bean10> getList(Connection con) {
List<Bean10> list = new ArrayList<>();
String sql = "SELECT col1, col2, col3, col4, col5, col6, col7 FROM mytable10";
try (Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery(sql)) {
while (rs.next()) {
Bean10 bean = new Bean10();
bean.setCol1(rs.getInt("col1"));
bean.setCol2(rs.getDouble("col2"));
bean.setCol3(rs.getDouble("col3"));
bean.setCol4(rs.getString("col4"));
bean.setCol5(rs.getString("col5"));
bean.setCol6(rs.getDate("col6").toLocalDate());
bean.setCol7(rs.getTimestamp("col7").toLocalDateTime());
list.add(bean);
}
} catch (Exception e) {
e.printStackTrace();
}
return list;
}
}
public List<Bean10> getList(Connection con) 메소드 추가로 작성함
select 하여 테이블을 조회하는 sql 코드, sql 실행
Bean10 객체 bean 생성, 조회한 컬럼 값들을 bean.set 메소드로 저장, 그리고 bean 을 리스트에 추가
컬럼값들이 저장된 리스트 반환
JDBC36Servlet
doGet
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// 0.
ServletContext application = request.getServletContext();
DataSource ds = (DataSource) application.getAttribute("dbpool");
MyTable10Dao dao = new MyTable10Dao();
List<Bean10> list = null;
// 3.
try (Connection con = ds.getConnection()) {
list = dao.getList(con);
} catch (Exception e) {
e.printStackTrace();
}
// 4.
request.setAttribute("list", list);
// 5.
String path = "/WEB-INF/view/jdbc08/v36.jsp";
request.getRequestDispatcher(path).forward(request, response);
}
MyTable10Dao 객체 dao 생성
리스트 생성 (bean 받을거니까 Bean10 타입)
try 에서 dao.getList 메소드 실행, 컬럼값들이 저장된 리스트 반환받아 list 에 저장
리스트 list setAttribute 로 전달
v36.jsp 로 포워딩
v36.jsp
<body>
<div class="container">
<div class="row">
<div class="col">
<table class="table">
<thead>
<tr>
<th>c1</th>
<th>c2</th>
<th>c3</th>
<th>c4</th>
<th>c5</th>
<th>c6</th>
<th>c7</th>
</tr>
</thead>
<tbody>
<c:forEach items="${list }" var="bean">
<tr>
<td>${bean.col1 }</td>
<td>${bean.col2 }</td>
<td>${bean.col3 }</td>
<td>${bean.col4 }</td>
<td>${bean.col5 }</td>
<td>${bean.col6 }</td>
<td>${bean.col7 }</td>
</tr>
</c:forEach>
</tbody>
</table>
</div>
</div>
</div>
</body>
리스트로 받아온 컬럼값들을 테이블로 출력
아까 35 servlet 실행했고, 이제 36 servlet 실행하면 다음과 같이 뜸
정리해보자
35Servlet doGet → 35jsp → 35Servlet doPost (Bean10, MyTable10Dao insert)
→ 36Servlet doGet (MyTable10Dao getList) → 36jsp
35Servlet doGet - 35jsp 로 포워딩
35jsp - form 으로 각 컬럼에 넣을 값을 받아서 post 방식으로 넘김
35Servlet doPost - request.getParameter 로 jsp 에서 입력한 값 받아옴,
bean.setCol (bean10 클래스의 setCol 메소드) 로 컬럼 값들을 저장,
dao.insert (dao 클래스의 insert 메소드) 로 insert 실행
Bean10 - setCol, getCol
MyTable10Dao insert - sql insert 코드, 무슨 값을 넣을지는 bean.getCol 로 받아서 pstmt 로 채움
36Servlet doGet - dao.getList 에서 list 반환받아 저장, setAttribute 로 저장하여 전달, 36jsp 로 포워딩
MyTable10Dao getList - SELECT sql 실행하여 각 컬럼값을 bean.setCol 에 저장, list 에 bean 을 추가하여 list 반환
36jsp - list 를 받아서 각 컬럼 값들을 출력하여 테이블로 보여줌
JDBC37Servlet, JDBC38Servlet
35, 36 반복 연습이므로 자세한 설명 생략
테이블 새로 만들기 - insert 하기 - 결과 확인하기
필요한 파일: v37.jsp, JDBC37Servlet, Bean11, MyTable11Dao, JDBC38Servlet, v38.jsp
> SQL 에서 테이블 mytable11 만들기
> v37.jsp
<body>
<h1>mytable11 insert</h1>
<form action="" method="post">
<input type="text" name="name">
<br>
<input type="number" name="age" min="0">
<br>
<input type="date" name="birth">
<br>
<input type="submit" value="입력">
<br>
</form>
</body>
> JDBC37Servlet
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String path = "/WEB-INF/view/jdbc08/v37.jsp";
request.getRequestDispatcher(path).forward(request, response);
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// 0.
ServletContext application = request.getServletContext();
DataSource ds = (DataSource) application.getAttribute("dbpool");
MyTable11Dao dao = new MyTable11Dao();
boolean ok = false;
// 2.
String name = request.getParameter("name");
String age = request.getParameter("age");
String birth = request.getParameter("birth");
Bean11 bean = new Bean11();
bean.setName(name);
bean.setAge(Integer.parseInt(age));
bean.setBirth(LocalDate.parse(birth));
// 3.
try (Connection con = ds.getConnection()) {
dao.insert(con, bean);
} catch (Exception e) {
e.printStackTrace();
}
// 4
// 5
String location = request.getContextPath() + "/jdbc08/s38";
response.sendRedirect(location);
}
35 서블릿과 달리, 마지막에 /jdbc08/s38 경로로 리디렉트하여, 값을 적어 제출하면 결과가 바로 창에 뜨도록 했음
> Bean11
public class Bean11 {
private String name;
private Integer age;
private LocalDate birth;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public LocalDate getBirth() {
return birth;
}
public void setBirth(LocalDate birth) {
this.birth = birth;
}
}
> MyTable11Dao
public class MyTable11Dao {
public boolean insert(Connection con, Bean11 bean) {
String sql = "INSERT INTO mytable11 (name, age, birth) VALUES (?, ?, ?)";
try (PreparedStatement pstmt = con.prepareStatement(sql)) {
pstmt.setString(1, bean.getName());
pstmt.setInt(2, bean.getAge());
pstmt.setDate(3, Date.valueOf(bean.getBirth()));
return pstmt.executeUpdate() == 1;
} catch (Exception e) {
e.printStackTrace();
}
return false;
}
public List<Bean11> getList(Connection con) {
List<Bean11> list = new ArrayList<>();
String sql = "SELECT name, age, birth FROM mytable11";
try (Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery(sql);) {
while (rs.next()) {
Bean11 bean = new Bean11();
bean.setName(rs.getString("name"));
bean.setAge(rs.getInt("age"));
bean.setBirth(rs.getDate("birth").toLocalDate());
list.add(bean);
}
} catch (Exception e) {
e.printStackTrace();
}
return list;
}
}
> JDBC38Servlet
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// 0
ServletContext application = request.getServletContext();
DataSource ds = (DataSource) application.getAttribute("dbpool");
MyTable11Dao dao = new MyTable11Dao();
List<Bean11> list = null;
// 2
// 3.
try (Connection con = ds.getConnection()) {
list = dao.getList(con);
} catch (Exception e) {
e.printStackTrace();
}
// 4
request.setAttribute("list", list);
// 5
String path = "/WEB-INF/view/jdbc08/v38.jsp";
request.getRequestDispatcher(path).forward(request, response);
}
> v38.jsp
<body>
<h1>mytable11 list</h1>
<table class="table">
<thead>
<tr>
<th>NAME</th>
<th>AGE</th>
<th>BIRTH</th>
</tr>
</thead>
<tbody>
<c:forEach items="${list }" var="bean">
<tr>
<td>${bean.name }</td>
<td>${bean.age }</td>
<td>${bean.birth }</td>
</tr>
</c:forEach>
</tbody>
</table>
</body>
* sql 로 insert 해도 38 서블릿 실행하면 결과가 표시됨
- 38 서블릿에서 dao.getList 에서 리스트 받아와 jsp 로 넘겨서 결과가 표시됨, dao.getList 에서는 SELECT 실행하기 때문에 가능함
13constraints.sql
https://www.w3schools.com/sql/sql_constraints.asp
♠ constraints 제약 사항
NOT NULL : 열에 NULL 값을 가질 수 없음
UNIQUE : 해당 열의 값들이 서로 달라야 함 (중복 불가)
PRIMARY KEY : NOT NULL and UNIQUE, 테이블의 각 행을 고유하게 식별하는 역할
FOREIGN KEY : 테이블 간의 연결을 유지하는 역할, 다른 테이블의 PRIMARY KEY 컬럼
CHECK : 열의 값이 특정 조건을 만족해야 함
DEFAULT : 값이 정해져있지 않은 열의 기본값을 설정
CREATE INDEX : 데이터베이스의 데이터를 빠르게 만들고 검색하는 데 사용됨
컬럼명 datatype constraint
CREATE TABLE 테이블명 (
컬럼1이름 컬럼1datatype constraint,
컬럼2이름 컬럼2datatype constraint,
컬럼3이름 컬럼3datatype constraint,
...
);
♠ NOT NULL
CREATE TABLE mytablec1 (
col1 VARCHAR(255),
col2 VARCHAR(255) NOT NULL
);
INSERT INTO mytablec1 (col1) VALUES ('aaa'); -- 불가
INSERT INTO mytablec1 (col2) VALUES ('bbb'); -- 가능 (col1 은 null)
INSERT INTO mytablec1 (col1, col2) VALUES ('aaa', 'bbb'); -- 가능
♠ UNIQUE
CREATE TABLE mytablec2 (
col1 VARCHAR(255),
col2 VARCHAR(255) UNIQUE
);
INSERT INTO mytablec2 (col1, col2) VALUES ('aaa', 'aaa');
INSERT INTO mytablec2 (col1) VALUES ('aaa'); -- 가능 (col2 는 null)
INSERT INTO mytablec2 (col2) VALUES ('aaa'); -- 불가능 (중복)
INSERT INTO mytablec2 (col1, col2) VALUES ('zzz', 'aaa'); -- 불가능 (중복)
* 만약 null 이 값이 아니고 "값이 없음" 이라면 중복 가능하다
♠ PRIMARY KEY
CREATE TABLE mytablec3 (
col1 VARCHAR(5),
col2 VARCHAR(5) NOT NULL UNIQUE -- PRIMARY KEY 로 작성해도 됨
);
INSERT INTO mytablec3 (col1, col2) VALUES ('aaa', 'aaa');
INSERT INTO mytablec3 (col1) VALUES ('aaa'); -- 불가능 (col2 null)
INSERT INTO mytablec3 (col2) VALUES ('aaa'); -- 불가능 (중복)
INSERT INTO mytablec3 (col1, col2) VALUES ('zzz', 'aaa'); -- 불가능 (중복)
♠ CHECK
CHECK (조건)
CREATE TABLE mytablec4 (
col1 INT,
col2 VARCHAR(5)
CHECK (col1 > 30 AND col1 < 100)
);
INSERT INTO mytablec4 (col1, col2) VALUES (10, 'abc'); -- 불가능
INSERT INTO mytablec4 (col1, col2) VALUES (50, 'abc'); --가능
♠ DEFAULT
CREATE TABLE mytablec5 (
col1 INT DEFAULT 0,
col2 DATE DEFAULT now(),
col3 VARCHAR(5)
);
INSERT INTO mytablec5 (col1, col2, col3) VALUES (10, "2020-02-20", 'aaa');
INSERT INTO mytablec5 (col3) VALUES ('abc'); -- col1, col2 는 지정한 기본값으로 저장됨
INSERT INTO mytablec5 () VALUES (); -- 모두 기본값으로 저장됨
♠ DESC : 테이블 정보 조회
DESC 테이블명;
해당 테이블의 각 컬럼의 field, type, null, key, default 등의 정보에 대해 조회할 수 있다
14primary-key.sql
PRIMARY KEY : 기본키, 주키
테이블을 만들 때 PRIMARY KEY 를 설정해주기! (없으면 임의로 PRIMARY KEY 로 설정할 컬럼을 생성해주자)
NOT NULL UNIQUE 혹은 PRIMARY KEY 작성
↓ DESC 로 조회하면 다음과 같이 NULL - NO, KEY - PRI
- Customers 테이블 조회하면
- Suppliers 테이블 조회하면
update, delete 할 때 주로 PRIMARY KEY 를 사용한다
♠ AUTO_INCREMENT
PRIMARY KEY 인 컬럼에 작성하며, 새 레코드를 추가할 때 고유 번호가 자동으로 생성되도록 한다
컬럼명 datatype PRIMARY KEY AUTO_INCREMENT
CREATE TABLE mytable (
id INT PRIMARY KEY AUTO_INCREMENT,
name VARCHAR(30) NOT NULL,
address VARCHAR(255) NOT NULL
);
insert 할 때 PRIMARY KEY 컬럼의 값을 작성하지 않아도 자동으로 저장된다
만약 AUTO_INCREMENT 가 아닌 PRIMARY KEY 칼럼이라면 이 칼럼 값을 직접 넣어주지 않으면 안된다 (NOT NULL 이기때문)
15alter-table.sql
♠ ADD COLUMN : 컬럼 추가하기
ALTER TABLE 테이블명 ADD COLUMN (
추가할컬럼명1 datatype,
추가할컬럼명2 datatype,
...
);
♠ DROP COLUMN : 컬럼 삭제하기
ALTER TABLE 테이블명 DROP COLUMN 삭제할컬럼명;
♠ ADD ~ FIRST / AFTER / BEFORE : 특정 위치에 컬럼 추가하기
ALTER TABLE 테이블명 ADD 추가할컬럼명 datatype FIRST;
ALTER TABLE 테이블명 ADD 추가할컬럼명 datatype AFTER 기존컬럼명;
'course 2021 > JDBC\DB' 카테고리의 다른 글
DB08 - 30일(sql28~34) - count, min, max, avg, sum, group by, having (0) | 2021.12.13 |
---|---|
DB07 - 29일(sql16~27, jdbc39) - alter, foreign key, join, union (0) | 2021.12.11 |
DB05 - 25일(jdbc27~30, sql08~11) - delete, create (0) | 2021.12.08 |
DB04 - 24일(sql06~07, jdbc21~26) - insert, update (0) | 2021.12.07 |
DB03 - 23일(jdbc11~20) (0) | 2021.12.06 |