본문 바로가기
Web & Mobile/MySQL

Lecture 38 - MySQL(1) 기초, Java에서 MySQL 활용법

by Bennyziio 2023. 6. 20.
반응형

2019/05/09 - [웹 프로그래밍/MySQL] - MySQL Windows 7 설치법

 

MySQL Windows 7 설치법

MySQL 윈도우7 설치 방법을 설명하겠습니다. 아래 절차서를 따라서 해보시기 바랍니다. 다운 받으면 위와 같이 설치파일이 생깁니다. 더블 클릭하여 설치를 시작하겠습니다. 위 3가지 항목을 전부 체크하여 Exec..

bennyziiolab.tistory.com

MySQL 설치법은 위 링크를 확인하세요

C:\Users\kitcoop>mysql -u root -p Enter password: ******

mysql> show databases;

mysql> use sakila;
Database changed
mysql> show tables;

Oracle의 top N query처럼 MySQL에서 limit을 사용할 수 있다.
limit 시작위치, 개수 (0부터 시작)

mysql> select * from actor limit 0, 1;

mysql> select * from actor limit 1, 1;

mysql> select * from actor limit 1, 10;

순서 1. order by > 2. desc > 3. limit

mysql> select * from actor order by first_name desc limit 1, 5;

여기 내용 필독 할 것!

http://www.incodom.kr/DB_-_%EB%8D%B0%EC%9D%B4%ED%84%B0_%ED%83%80%EC%9E%85/MYSQL

DB - 데이터 타입/MYSQL

# 데이터 타입(DataType) 정의

www.incodom.kr

mysql> create database sample;

mysql> use sample
Database changed

mysql> create table testtbl1 (
    -> seq smallint(5) unsigned,
    -> name varchar(10),
    -> address varchar(50)
    -> );
Query OK, 0 rows affected (0.56 sec)

unsigned : 음수를 안쓴다는 의미(양수만)

mysql> use sample;
Database changed
mysql> insert into testtbl1 values (10, '홍길동', '서울');
mysql> select * from testtbl1;

mysql> create table testtbl2 (
    -> seq      smallint(5) unsigned primary key auto_increment,
    -> name     varchar(10),
    -> address  varchar(50)
    -> );

mysql> insert into testtbl2 values (0, '홍길동', '서울');

mysql> insert into testtbl2 values (0, '홍길동', '서울');

mysql> insert into testtbl2 values (10, '홍길동', '서울');

mysql> insert into testtbl2 values (10, '홍길동', '서울');
ERROR 1062 (23000): Duplicate entry '10' for key 'PRIMARY'

auto_increment(sequece의 기능) 때문에 0을 넣었을때에는 무시하고 increment가 실행되고, 특정값을 입력하게 되면 primary key 때문에 고유값 에러가 생긴다.
           ==> 가능한 0으로 입력시키면 된다.
그러므로 primary key를 넣을때는 0으로 넣는 버릇을 가지면 자동으로 순서대로 값을 넣는다.

mysql> select 1 + 1;

mysql> select now();

자바 이클립스에서 사용하기 위해 jar를 추가해주기 위해 위 파일을 복사해준다

JDBCEx02 - Java와 MySQL 연결

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

public class JDBCEx01 {

	public static void main(String[] args) {
		String url = "jdbc:mysql://localhost:3306/sample?useSSL=false&useTimezone=true&serverTimezone=UTC";
		String user = "root";
		String password = "123456";
		
		Connection conn = null;
		
		try {
			Class.forName("com.mysql.cj.jdbc.Driver");
			conn = DriverManager.getConnection(url, user, password);
			
			System.out.println("데이터베이스 연결 성공");
			
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			if(conn != null) try {conn.close();} catch(SQLException e) {};
		}
	}
}

데이터 입력

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;

public class JDBCEx01 {

	public static void main(String[] args) {
		String url = "jdbc:mysql://localhost:3306/sample?useSSL=false&useTimezone=true&serverTimezone=UTC";
		String user = "root";
		String password = "123456";
		
		Connection conn = null;
		PreparedStatement pstmt = null;
		
		try {
			Class.forName("com.mysql.cj.jdbc.Driver");
			conn = DriverManager.getConnection(url, user, password);
			
			System.out.println("데이터베이스 연결 성공");
			
			String sql = "insert into testtbl1 values (?, ?, ?)";
			pstmt = conn.prepareStatement(sql);
			pstmt.setString(1, "10");
			pstmt.setString(2, "박문수");
			pstmt.setString(3, "인천");
			
			pstmt.executeUpdate();
			
			System.out.println("데이터베이스 입력 성공");
			
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			if(pstmt != null) try {pstmt.close();} catch(SQLException e) {};
			if(conn != null) try {conn.close();} catch(SQLException e) {};
		}
	}
}

반응형

'Web & Mobile > MySQL' 카테고리의 다른 글

Lecture 39 - MySQL(2) 자바로 메일 보내기, Maven  (0) 2023.06.20
MySQL Windows 7 설치법  (0) 2023.06.20

댓글