자바

* mysql 설치 

http://mysql.com 

- community edition 다운로드

- mysql server와 mysql Connector J 설치

 

* HeidiSQL 설치

http://www.heidisql.com

- 도구 - 사용자관리자 메뉴에서 사용자 추가

  아이디 : java

  비번 : java1234

  호스트 : localhost

  전체권한에 체크

 

* jdbc library 복사 : C:\Program Files (x86)\MySQL\Connector.J 5.1   에서 jar 파일을 WebContent/WEB-INF/lib 디렉토리에 복사

 

-- create table 테이블 이름
-- 컬럼 자료형(사이즈) 제약 조건
-- char : 고정 사이즈 문자열
-- varchar : 가변 사이즈 문자열

-- not null : 필수 입력

create table car (

	 license_number varchar(50) not null,
	 company varchar(50),
	 type varchar(50),
	 year int,
	 efficiency int,
	 primary key(license_number)
 

);

-- 작은 따옴표 :문자열
insert into 테이블 (컬럼들) values (값들)


insert into car (license_number, company, type, year, efficiency )
	 values ('99가1234', '현대', '오토', 2017, 20 );




select * from books;








 

 

 

CREATE TABLE `books` (
	`book_id` INT(11) NOT NULL AUTO_INCREMENT,
	`title` VARCHAR(50) NULL DEFAULT NULL,
	`publisher` VARCHAR(30) NULL DEFAULT NULL,
	`year` VARCHAR(10) NULL DEFAULT NULL,
	`price` INT(11) NULL DEFAULT NULL,
	PRIMARY KEY (`book_id`)
)
COLLATE='utf8_general_ci'
ENGINE=InnoDB
AUTO_INCREMENT=6
;

 

 

 

 

 class ConnectDatabase

package java19;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;



//mysql 서버에 접속 테스트
public class ConnectDatabase {
   
	public static void main(String[] args) {
		// DB 연결 문자열 jdbc:mysql://host/db
		String url ="jdbc:mysql://localhost:3305/java";
		String id="java";// mysql 계정 id
		String password="1111";//mysql 계정 비번
		//DB접속 처리
		Connection conn=null; //java.sql.Connection
		//SQL 명령어를 실행시키는 객체
		Statement stmt =null;
		//select 명령어의 결과를 처리하는 객체
		ResultSet rs=null;
		try {
			//mysql 연결 드라이버 클래스 이름
			Class.forName("com.mysql.jdbc.Driver");
			System.out.println("드라이버 로딩 성공");
			//mysql 서버에 접속 getConnection(연결문자열, 아이디, 비번)
			conn=DriverManager.getConnection(url, id, password);
			System.out.println("mysql 연결 성공");
			String sql ="select * from books";
			//sql 명령어를 실행시키기 위한 객체 생성
			stmt =conn.createStatement();
			//select 명령어의 실행결과를 한 레코드씩 읽어서 처리하는 객체
			rs=stmt.executeQuery(sql);
			System.out.println("도서코드\t도서이름");
			while(rs.next()){ //결과셋.next() 다음 레코드가 존재하면 true
//결과셋.get자료형(컬럼이름) 컬럼의 값을 조회				
				int book_id=rs.getInt("book_id");
				String title=rs.getString("title");
				System.out.println(book_id + "\t"+ title);
			}					
		} catch(Exception e){
			e.printStackTrace();
		}finally{
			//rs ->stmt ->con 순으로 닫음 (오픈한 역순으로)
			try{
				if(rs!=null)rs.close();
				if(stmt!=null)stmt.close();
				if(conn!=null)conn.close();
			}catch(Exception e2){
				e2.printStackTrace();
			}
		}
	}
	
	
	
	
}






 

 

드라이버 로딩 성공
mysql 연결 성공
도서코드    도서이름
1    운영체제
2    안드로이드
3    스프링
4    JSP
5    java
6    java
7    프리턴
8    C++

 

 

class SQLInsertTest 

 

package java19;

import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;

public class SQLInsertTest {	
	public static void main(String[] args) {
		String url ="jdbc:mysql://localhost:3305/java";
		String id="java";
		String password="1111";
		Connection conn=null; // 
		Statement stmt=null;
		try{
			Class.forName("com.mysql.jdbc.Driver");
			System.out.println("드라이버가 존재합니다.");
			
			conn=DriverManager.getConnection(url, id, password);
			System.out.println("mysql 연결 성공");
			
			String title="C++";
			String publisher="C++출판사";
			int year=2017;
			int price=45000;
			
			String sql ="insert into books (title, publisher, year, price )"
					+ " values ('java', '자바출판사', 2017, 40000 )";
			String sql2 =String.format("insert into books (title, publisher, year, price )"
					+ "values ('%s', '%s', %d, %d )" , title ,  publisher , year, price);
					
			
			
			stmt=conn.createStatement();
			//executeUpdate() 추가, 수정, 삭제
			// executeQuery() select 
			// execute()  추가
			stmt.execute(sql2);
			System.out.println("추가되었습니다");
			
		}catch(Exception e){
			e.printStackTrace();
		}finally{
			try{
				if(stmt!=null)stmt.close();
				if(conn!=null)conn.close();
			}catch (Exception e) {
				e.printStackTrace();
			}
		}
		
	
		
		
	}
	
	
}




 

 

드라이버가 존재합니다.
mysql 연결 성공
추가되었습니다

 

 

 

 

 

 

 

 

about author

PHRASE

Level 60  머나먼나라

세상을 떠난 성인을 대신하여 끊어진 학문, 즉 성인의 도(道)를 다시 이어서 밝히는 것이다. 장횡거(張橫渠)가 한 말. -근사록

댓글 ( 4)

댓글 남기기

작성