[mysql]select for update for update transaction

DB/Mysql 2016. 7. 28. 18:38 Posted by Request

 

특정 row에 lock를 걸어서

다른 세션의 'select for update' 혹은 'select lock in share mode' 쿼리를 블락하고

싶은 경우 사용된다.

 

예)

select * from tableNm where column_name = '1' for update

 

 

출처 :

http://blog.daum.net/hazzling/17187062

 

 

 

 

 

 

 

MyBatis mysql selectKey LAST_INSERT_ID() 설명

DB/Mysql 2015. 8. 6. 21:43 Posted by Request

출처 - http://www.raistudies.com/mybatis/inserting-auto-generated-id-using-mybatis-return-id-to-java/

 

 

 

  1. AUTO_INCREMENT facility in MySQL Database
  2. IDENTITY facility in MS SQL Server.
  3. A combination of sequence and trigger to generate new unique id in Oracle server.

 

Tools Used:

  1. MyBatis 3.1.0
  2. MySql Java Connector 5.1

 

First of all, we have to change the schema of table Product to make the id field auto generated. Following is the DDL command to make the Product table with auto generated id:

1 CREATE TABLE Product(id BIGINT NOT NULL AUTO_INCREMENT , brand VARCHAR(20),
2 model VARCHAR(20), name VARCHAR(30) , PRIMARY KEY (id));

Here, I have used AUTO_INCREMENT to generate unique id in MySQL database.

Now, to use auto generated id in our mapping file ProductServices.xml to modify our <insert/> command to use it:

1 <?xml version="1.0" encoding="UTF-8"?>
2 <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
3 "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
4  
5 <mapper namespace="com.raistudies.services.ProductServices">
6  
7     <insert id="save" parameterType="product" useGeneratedKeys="true" keyProperty="id"�  keyColumn="id">
8         INSERT INTO Product (brand,model,name)
9         VALUE (#{brand}, #{model}, #{name} )
10         <selectKey keyProperty="id" resultType="long" order="AFTER">
11             SELECT LAST_INSERT_ID();
12         </selectKey>
13     </insert>
14  
15 </mapper>
  • You can identify three changes that we have to made in <insert/> command tag to use auto generated id and then return the newly generated id to java.
  • We have added useGeneratedKeys=”true”, this specify mybatis that the id will be auto generated by database.We also have to specify keyProperty=”id” and keyColumn=”id” which tells the property name of POJO class Product that will be used as ID and also the column name of table product that is used as id.
  • We have to remove id field from insert DDL, so that database can generate a new id for the column and put it.
  • We have used : 
    <selectKey keyProperty=”id” resultType=”long” order=”AFTER”>

                SELECT LAST_INSERT_ID();
            </selectKey>
    That will return newly generated id and save it to the id property of POJO class Product. The query written in between <selectKey/> tags is database specific and it may be change according to database. In this example, we have used the query that will work for MySQL database server only.

To test the functionality, we have made a little modification in our runner class:

1 package com.raistudies.runner;
2  
3 import java.io.IOException;
4 import java.io.Reader;
5  
6 import org.apache.ibatis.io.Resources;
7 import org.apache.ibatis.session.SqlSession;
8 import org.apache.ibatis.session.SqlSessionFactory;
9 import org.apache.ibatis.session.SqlSessionFactoryBuilder;
10  
11 import com.raistudies.domain.Product;
12 import com.raistudies.services.ProductServices;
13  
14 public class AppTester {
15 private static SqlSessionFactory sessionFac = null;
16 private static Reader reader;
17 private static String CONFIGURATION_FILE = "sqlmap-config.xml";
18  
19     static{
20         try {
21             reader = Resources.getResourceAsReader(CONFIGURATION_FILE);
22             sessionFac = new SqlSessionFactoryBuilder().build(reader);
23         } catch (IOException e) {
24             e.printStackTrace();
25         }
26     }
27  
28     public static void main(String[] args) {
29         SqlSession session = sessionFac.openSession();
30         try {
31         ProductServices productServiceObj = session.getMapper(ProductServices.class);
32         Product product = new Product();
33         product.setBrand("LG");
34         product.setModel("P500");
35         product.setName("Optimus One");
36         productServiceObj.save(product);
37         System.out.println("The new id is : " + product.getId());
38         session.commit();
39  
40         } finally {
41             session.close();
42         }
43     }
44  
45 }

The new code will not specify the value of id field and also print the new generated id in console.

Run the code and you will get output like this:

Auto generated id in MyBatis and return the new id to java

Using Auto Generated ID in MyBatis and return the new ID to java

You can also try the example yourself. Just download the code from bellow links, import the project in Eclipse and create the product table using given DDL command:

Code + lib: Download

Code: Download

Toad Mysql Tip

DB/Mysql 2015. 7. 30. 13:45 Posted by Request

토드 6 Mysql alt + d + f 쿼리정렬... 자꾸 까먹네 ㅎㅎ;;

 

oracle -> mysql 정리

DB/Mysql 2015. 7. 13. 15:02 Posted by Request

oracle에서 사용 했던 방식을 mysql로 적용 할려 하니 비슷하면서도 다른 부분이 많아 정리 하고자 한다.

 

1.문자열 합치기 

Oracle : '%'||A||'%'

Mysql  : CONCAT('%', A , '%')

 

2. null check

Oracle : SELECT NVL('컬럼명', '') FROM DUAL;

MySql : SELECT IFNULL('컬럼명', '') FROM DUAL;

 

3.현재 날짜시간

Oracle : SYSDATE

Mysql  : NOW() 

 

4.날짜 포맷

Oracle : TO_CHAR(sysdate,'MMDDYYYYHH24MISS')

Mysql  : DATE_FORMAT(now(),'%Y%m%d%H%i%s')  

-> 여기서 대문자Y는 4자리 년도, 소문자 y는 2자리 년도 20150713142107

 

DATE_FORMAT(now(),'%Y%m%d') -> 20150713

 

5.날짜 포멧 : 요일

Oracle : 요일이 1~7로 인식함  -> TO_CHAR(SYSDATE 1, 'D') 

Mysql : 요일이 0~6으로 인식   -> DATE_FORMAT(DATE_SUB(NOW(), INTERVAL 1 DAY), '%w')

* 참고로 자바스크립트가 0~6으로 인식하기에 Oracle 쿼리에서 -1을 해서 맞추는 경우가 많음

 

 

6. 형변환
Oracle : To_char, To_number 등
Mysql : CAST
SELECT TO_CHAR(1234) FROM DUAL 
-> SELECT CAST(1234 AS CHAR) FROM DUAL

 

7. MYSQL은 대소문자 구분함

8. ROWNUM
Oracle : where 절에 rownum > 5 and rownum =< 10 
Mysql : where절 없이 limit 5,10


9. Sequence(시퀀스)는 둘 다 사용자함수를 만들어서 아래와 같이 사용

Oracle : 시퀀스명.nextval

Mysql : 시퀀스명.currval


10. 문자열 자르기

Oracle: SUBSTR(컬럼명, 1, 10)

Mysql: SUBSTRING(컬럼명, 1,10)

SQL Terms/Concepts MongoDB Terms/Concepts
database database
table collection
row document or BSON document
column field
index index
table joins embedded documents and linking

primary key

Specify any unique column or column combination as primary key.

primary key

In MongoDB, the primary key is automatically set to the _id field.

aggregation (e.g. group by)

aggregation pipeline

See the SQL to Aggregation Mapping Chart.

 

 

 

참조 : http://docs.mongodb.org/manual/reference/sql-comparison/

(Oracle)오라클 SID 중복 regedit 제거법

DB/Oracle 2012. 5. 24. 16:58 Posted by Request
1.Windows 계열일 경우
이경우 레지스트리에 등록된 SID를 지우셔야 할겁니다.
제가 찾아본것으로는 아래 레지스트리를 지우시고
다시 DB를 생성하시면 될듯합니다.
\HKEY_LOCAL_MACHINE\SOFTWARE\ORACLE\HOMEID\SID
\HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\OracleServiceSID
이두가지를 지우시면 될듯합니다.
여기서 SID는 예전에 설치하셨을때 사용하신 SID겠죠..
이게 남아있으면 같은 SID로 다시 DB를 만들수 없습니다.


2.Unix계열(리눅스도 포함)
보통 SID는 oratab이란 파일에 저장되는데
이파일은 시스템마다 조금씩 틀리지만
/etc, /var/opt/oracle 밑에 존재합니다.
그냥 이파일을 지우시던지...아니면
편집하셔서 기존에 설치하셨던 SID 리스트를
지우시면 됩니다.
10g에서는 $ORACLE_HOME/install 밑에 있습니다.

 

 

 

 

출처 :http://cmsyko.egloos.com/5305796

MYSQL 기본 명령어 정리

DB/Mysql 2012. 4. 5. 14:29 Posted by Request

첫 번째, mysql 접속

-  [root@localhost ~]#mysql -u root -p

 

두번째, 사용할 데이터베이스를 선택합니다.

- show databases;

-use stdent;

 

세번째, 테이블 생성

create table student(
bbs_id int auto_increment primary key,
student_id int(11) not null,
name varchar(20) not null
);

네번째, 데이터 입력

INSERT INTO student(
bbs_id,student_id, name
) VALUES (
0,20120405,"홍길동");

 

 

 

 

JDBC를 이용한 Java와 mysql 연동하기

DB/Mysql 2012. 4. 5. 14:21 Posted by Request

0. JDBC를 이용한 Java와 mysql 연동하기 전에 수행되어야 할 것

0.1 JDK가 설치되어 있어야 함.

- http://www.oracle.com/technetwork/java/javase/downloads/jdk-7u3-download-1501626.html


0.2. Eclipse가 설치되어 있어야 함.

- http://www.eclipse.org/downloads/


0.3. MySQL이 설치되어 있어야 함.

- http://dev.mysql.com/downloads/installer/



1. MySQL을 위한 JDBC Driver를 다운로드

- http://dev.mysql.com/downloads/connector/j






2. 받은 파일을 압축풀고, mysql-connector-java-5.1.19-bin.jar 파일을

[java]-[jdk1.7.0_02] - [jre] - [lib] - [ext] 폴더에 복사




3. Eclipse에 본인이 만든 프로젝트의 설정을 변경



4. [Java Build Path]에서 해당폴더에 복사한 jar 파일을 추가함








- jar 파일을 추가하면 다음과 같이 추가된 library를 확인할 수 있음




5. 다음 그림과 같이 [test] DB안에 있는 [student] 테이블 항목들을 JDBC를 이용해 출력하고자 함




6. 다음과 같은 코드를 이용해서 테이블에 있는 항목들을 출력하고자 함



7. 실행하면 다음과 같이 MySQL과 연동성공!!

mysql> INSERT INTO test VALUES('테스트', 100);

ERROR 1366 (HY000): Incorrect string value: '\xC5\xD7\xBD\xC6\xAE' for column 'item' at row 1

DB에 테이블 내용을 입력하는데 이러한 오류가...

테이블 내용에 한글을 넣으니 오류가 생기는 것 같은데...

1.증상

mysql 을 utf-8 로 설정하고 설치했는데도 불구하고 데이터를 insert 할 때 한글깨지는 증상이란다.

2. 해결방법

mysql> SET character set euckr;

Query OK, 0 rows affected (0.01 sec)

mysql> INSERT INTO test VALUES('테스트', 100);

Query OK, 1 rows affected (0.06 sec)

utf-8로 세팅을 하면은 기존의 값을 불러올 때는 되는데, 데이터를 입력할때는 깨어진다나 어쨌다나... 한글을 euckr 로 변환해야 안깨진다.

'SET character set euckr'이라고 입력해보자.

[oracle] 오라클 scott계정 Lock 해제

DB/Oracle 2011. 9. 7. 17:26 Posted by Request
오라클 scott계정 Lock 해제

User / Password를 system/manager이나 sys/sysdba로 접속후

sql>select username,account_status from dba_users username='SCOTT'

결과가 EXPIRED & LOCKED 일것이다 락을 풀어준다

sql>alter scott account unlock;

sql>alter SCOTT identified by TIGER;

sql>select username,account_status from dba_users username='SCOTT'

결과가 OPEN이 되어 있을것이다 OPEN상태에서 로그인이 가능

 

ORA-01045 error는 user를 생성하고 권한을 부여하지 않아서 그렇다.

로그인을 하기 위해서 세션을 생성해야 하는데 하지 않아서 생기는 error

따라서 다음과 같이 권한을 부여하면 된다,.

grant create session to user_name;