본문 바로가기

Spring/Model1 _2(MVC)

0822 JSP - MySQL WorkBench, Connector/J

728x90
반응형

워크벤치에서 실습용을 하나 만들어준다


워크벤치 주석문


-- ctrl + /
-- 왼쪽 번개 -> 전체 다 실행(ctrl shift enter) , 오른쪽 번개 -> 커서가 있는 구문만 실행 (ctrl enter)


ex) itwill_member 테이블에 있는 남자의 정보만 출력 하기

SELECT * FROM itwill_member where gender = 'm';

JDBC 라이브러리 (드라이버) - Connector J 다운로드

mysql.com
Platform Independent (Architecture Independent), ZIP Archive 다운로드

해당 파일을 복사해서

이클립스 lib에 붙여넣기


드라이버 로드

Class.ForName("com.mysql.cj.jdbc.Driver");

성공 표시가 있어야함


DB 연결

DriverManager.getConnection(url, user, password);

jdbc:mysql://localhost:3306/jspdb
http://localhost:8088/JSP/jsp4/dbConnection.jsp
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/jspdb", "root", "1234");


System.out.println(" 디비 연결 성공! ");

=> 디비가 연결이 된 것임


이런 코드들은 외워서 쓰는 게 아니라 mysql.com에 들어가서 확인 하면 된다.
mysql.com ->
MySQL Connector/J 8.0 Developer Guide / Connector/J Reference / Driver/Datasource Class Name

6.1 Driver/Datasource Class Name

The name of the class that implements java.sql.Driver in MySQL Connector/J is com.mysql.cj.jdbc.Driver.




네이버 블로그, 구글 블로그 참고하지말고
stack overflow 사이트 활용!


정보를 DB에 저장 (Create)


디비 연결 정보

		final String DRIVER = "com.mysql.cj.jdbc.Driver";
		final String DBURL = "jdbc:mysql://localhost:3306/jspdb";
		final String DBID = "root";
		final String DBPW = "1234";

이 값들은 불변한다.

다른 사람 코드를 볼때, 변수 이름이 대문자다? => '상수'인 것
값이 바뀌지 않고, 계속 반복되는 값들은 상수, 계속 바뀌는 값들은 변수로 바꿔주면 편리하다.


상수를 정해주고 연결 코드를 하단처럼 간편하게 바꿔줌

Connection con = DriverManager.getConnection(DBURL, DBID, DBPW);


SQL문 작성 & statement객체 생성
- SQL구문을 실행하도록 도와주는 객체
	String sql = "";


ex) itwill_member 테이블에 정보 저장 -insert 구문

String sql = "insert into itwill_member (name, gender, age, jumin) values ('ITWILL','m', '36', '900101-5555555')";



System.out.println("con : " + con);

뭔가를 보는데 코드란에 @가 있으면, 나눠서 볼줄 알아야함.
con : com.mysql.cj.jdbc.ConnectionImpl@5eff1e41



JSP 페이지 -> MySql

드라이버 설치
디비주소,아이디,비밀번호

-----------Connection이 포장해줌---------------
OK - 연결 정보
형태 : ConnectioImp1
--------------------------------------------------------

Statement stmt = con.createStatement();



SQL 문 실행
stmt.executeUpdate(sql);
System.out.println(" SQL 실행 완료! ");


실행 후 -> 워크벤치에서 실행(세번째 버튼) 눌리면 실행됨.


정보 입력받는 페이지 만들기

<insertForm>

<h1>insertForm.jsp</h1>
	
	<h2> 정보입력하는 페이지 </h2>
	
	<form action="insertPro.jsp" method="post">
		이름 : <input type = "text" name = "name"><br>
		성별 : <input type = "text" name = "gender"><br>
		나이 : <input type = "text" name = "age"><br>
		주민번호 : <input type = "text" name = "jumin"><br>
		
		<input type = "submit" value = "디비에 저장하기">

<insertPro>

	<h1>insertPro.jsp</h1>
	
<% 
	//한글처리!
	request.setCharacterEncoding("UTF-8");
	//전달 된 정보 저장하기 -> 출력하기
	String name = request.getParameter("name");
	String gender = request.getParameter("gender");
	String jumin = request.getParameter("jumin");
	
	int age = Integer.parseInt(request.getParameter("age"));
	
	%>
	
	<%=name %>, <%=gender %>, <%=jumin %>, <%= age %>
	<h2> 전달받은 정보를 DB에 저장 </h2>
	
	<%
			//1. 드라이브 로드 
			//2. 디비 연결 
		
			Class.forName("com.mysql.cj.jdbc.Driver");
			System.out.println("드라이브 로드 성공");
			
			Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/jspdb", "root", "1234");
		
			System.out.println("디비 연결 성공!");
			System.out.println("con : " + con);
			
			
			// 3. SQL문 작성 & stmt 객체 
			// itwill_member 테이블에 정보 저장 -insert 구문 
			
			String sql = "insert into itwill_member (name, gender, age, jumin) values ('"+name+"','"+gender+"', '"+age+"', '"+jumin+"')";
			
			// SQL 구문을 실행하도록 도와주는 객체 
			Statement stmt = con.createStatement();
			System.out.println("stmt 객체 생성 완료! ");
			

			// 4. SQL 쿼리 문 실행 
			stmt.executeUpdate(sql);
			System.out.println(" SQL 실행 완료! ");
	
	%>



홈페이지 들어가서 값 넣고 실행
-> 워크벤치에 들어가서 실행시키면 DB란에 내가 쓴 값이 나온다


더보기

Statement : SQL 구문을 실행하도록 도와주는 객체
Statement stmt = con.createStatement();
PreparedStatement : SQL 구문을 실행하도록 도와주는 객체 (사전작업)




?
('"+name+"','"+gender+"', '"+age+"', '"+jumin+"')"; 쓰기 힘드니까 ? 로 바꿔주는 작업

<insertPro2>

//1. 드라이브 로드 
//2. 디비 연결 
		
			Class.forName("com.mysql.cj.jdbc.Driver");
			System.out.println("드라이브 로드 성공");
			
			Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/jspdb", "root", "1234");
		
			System.out.println("디비 연결 성공!");
			System.out.println("con : " + con);
			
			
// 3. SQL문 작성 & stmt 객체 
// itwill_member 테이블에 정보 저장 -insert 구문 
			
			String sql = "insert into itwill_member (name, gender, age, jumin) values (?,?,?,?)";
			
//Statement :  SQL 구문을 실행하도록 도와주는 객체 
//Statement stmt = con.createStatement();
//PreparedStatement : SQL 구문을 실행하도록 도와주는 객체 (사전작업)
			
			PreparedStatement pstmt = con.prepareStatement(sql);
			
			System.out.println("stmt 객체 생성 완료! ");
			


			
// ???? (SQL 구문에 ?가 있는 경우 실행)
// pstmt.setXXXX(?의 위치, ?에 들어갈 값);
// => DB에 저장되는 타입에 따라서 메서드가 변경 setString, setInt, setDouble,..
// => set()개수는 ??개수와 동일
					
			pstmt.setString(1, name);
			pstmt.setString(2, gender);
			pstmt.setInt(3, age);
			pstmt.setString(4, jumin);

// 4. SQL 쿼리 문 실행 
//stmt.executeUpdate(sql);
			pstmt.executeUpdate();
			System.out.println(" SQL 실행 완료! ");
			
	%>

<숙제 - DB연결 동작 >

전달정보 name, gender, age, jumin 변수에 전달 된다고 가정


1. 드라이버 로드
2. 디비 연결
3. SQL 작성 & pstmt
???
4. SQL 실행

DB연결 동작 


전달정보 name, gender, age, jumin 변수에 전달 된다고 가정 



1. 드라이버 로드
class.forname("com.mysql.cj.jdbc.Driver");
2. 디비 연결
Connection con = DriverManager.getConnection(URL,ID,PW)

3. SQL 작성 & pstmt
  -String sql = insert into itwill_member (name, gender, age, jumin) values "(이름, 성별, 나이, 주민번호)";
                Statement stmt = con.createStatement();
   ??? 
  -String sql = "insert into itwill_member ( name, gender, age, jumin) values (?,?,?,?)";
                 PreparedStatement pstmt = con.preparedStatement(sql);

                 pstmt.setString(1, name);
                 pstmt.setString(2, gender);
                 pstmt.setInt(3, age);
                 pstmt.setString(4, jumin);
4. SQL 실행 
stmt.executeUpdate(sql);


pstmt.executeUpdate();






















728x90
반응형

'Spring > Model1 _2(MVC)' 카테고리의 다른 글

[JSP&Servlet] parameter 와 attribute 차이  (0) 2022.08.28
0825 JSP - MySQL - DELETE ~ 객체, 자바빈  (0) 2022.08.25
0822 JSP - mySQL 설치 ~  (0) 2022.08.22
0818 JSP - cookieForm => cookiePro ~ session  (0) 2022.08.18
[JSP] 8/9  (0) 2022.08.09