레이블이 MSSQL인 게시물을 표시합니다. 모든 게시물 표시
레이블이 MSSQL인 게시물을 표시합니다. 모든 게시물 표시

DB Table Lock 걸기

멀티 쓰레드 환경에서 다수의 DB 커넥션이 테이블 값에 접근하여 쿼리를 수행하려 할때
발생할 수 있는 동시성을 해결하기 위한 방법 중 하나로 "for update" 구문을 사용할 수 있다.

/* 이미 Lock을 걸어 수행 중인 쿼리가 있으면 대기한다. */
select * from table_a for update;

/* 이미 Lock을 걸어 수행 중인 쿼리가 있으면 3초까지만 대기하고 빠져 나온다.(오라클) */
select * from table_a for update wait 3;

/* 이미 Lock을 걸어 수행 중인 쿼리가 있으면 대기하지 않고 바로 빠져 나온다.(오라클) */
select * from table_a for update no wait;


/*
예를 들어 다음 데이터가 들어갈 시퀀스 값을 알고 싶은 경우,
Oracle 의 경우 nextval 기능을 사용하면 다음 시퀀스 값을 유니크하게 얻어 오지만
MySQL 에는 nextval 이 없어 for update 구문을 이용하도록 한다.
*/
select ifnull(max(my_seq+1),1) from table_a for update;


DB 커넥션 끊김 방지하기

보통 DB에서는 쿼리 요청이 없는 Connection 은 일정시간이 지나면 끊어 버린다.

# MySQL 경우 기본 커넥션유지는 interactive_timeout 28800 (8시간)이다.
https://dev.mysql.com/doc/refman/5.7/en/server-system-variables.html#sysvar_interactive_timeout
# 각종 타임 아웃 시간 보기
# 대기시간(연결 유지)은 wait_timeout
show variables like '%timeout%';

따라서 일정 주기만 커넥션을 유지를 위한 더미 쿼리(ex "Select 1;")를 요청해주도록 한다.
아니면 각 DB 마다 연결끊김 에러코드를 인지하여 다시 연결하도록 한다.

oracle
ORA-00028: your session has been killed
ORA-01012: not logged on
ORA-01033: ORACLE initialization or shutdown in progress
ORA-01034: ORACLE not available
ORA-01089: immediate shutdown in progress - no operations are permitted
ORA-03113: end-of-file on communication channel
ORA-03114: not connected to ORACLE
ORA-03127: no new operations allowed until the active operation ends
ORA-12571: TNS:packet writer failure

mssql
10054 : Connection Reset By peer (tcp 의 RST 로 비정상 종료로 연결을 끊는 경우)
10061 : Network Error

mysql
2003 : Can't connect to MySQL server
2013 : Lost connection to MySQL server during query
2006 : MySQL server has gone away


ODBC 사용시 각 DBMS 별 Connection String

ODBC 사용시 각 DBMS 별 Connection String

Oracle
Driver={Microsoft ODBC for Oracle};Server=10.10.10.10;Port=3306;Uid=ysoftman;Pwd=abcd1234;

MySQL
Driver={MySQL ODBC 5.2 ANSI Drive};Server=10.10.10.10;Port=3306;Database=testdb;User=ysoftman;Password=abcd1234

MS-SQL
Driver={SQL Server};Server=10.10.10.10,3306;DSN=dsn_test;Database=testdb;Uid=ysoftman;Pwd=abcd1234;


RDB(relational database) 로 NoSQL 흉내내기

[Microsoft SQL 을 -> NoSQL 처럼]
-XML 형식으로 데이터를 지원, XML 형식의 데이터를 찾고, 입력하고, 수정하고, 삭제 가능
-SQL Server 2000 이후 부터 지원
-XML 데이터는 내부적으로 Binary로 저장되며 일반적인 경우 약간의 압축이 제공되어 인스턴스당 2GB 저장 가능
-참고
 http://technet.microsoft.com/ko-kr/library/ms177454.aspx
-예제
/*
테이블 생성 시 XML 형식의 열을 포함하도록 한다.
XML 키워드로 만든 xmldata 로 여러가지 쿼리를 수행한다.
*/
create table YsoftmanTable(id int not null, xmldata xml)

/* id가 1인 행에 XML 형식의 데이터 입력하기 */
insert into YsoftmanTable select 1, '
<?Employee Info?>
<Employee>
 <Name>YoonByoungHoon</Name>
 <Sex>Male</Sex>
 <Phone>123456789</Phone>
</Employee>
'
/* id가 2인 행에 XML 형식의 데이터 입력하기 */
insert into YsoftmanTable select 2, '
<?Employee Info?>
<Employee>
 <Name>BillGates</Name>
 <Sex>Male</Sex>
 <Phone>55555</Phone>
</Employee>
'

/* 내용 확인 */
select * from YsoftmanTable

/* id가 2인 행에서 Employee 하위 요소인 Name 요소의 모든 내용 찾기 */
select xmldata.query('/Employee/Name') from YsoftmanTable where id=2

/* id가 2인 행에서 Employee 하위에 Address 요소를 첫번째 위치로 추가 */
update YsoftmanTable set xmldata.modify('insert <Address>Seattle</Address> as first into (/Employee)[1]') where id=2

/* id가 2인 행에서 Employee 하위에 Mobile 요소를 Phone 요소 앞에 추가 */
update YsoftmanTable set xmldata.modify('insert <Mobile>2222</Mobile> before (/Employee/Phone)[1]') where id=2

/* id가 2인 행에서 Employee 하위에 Mobile 요소의 값을 변경 */
update YsoftmanTable set xmldata.modify('replace value of (/Employee/Mobile/text())[1] with "333"') where id=2

/* id가 2인 행에서 Employee 하위 요소인 Name 요소의 모든 내용 삭제 */
update YsoftmanTable set xmldata.modify('delete /Employee/Name') where id=2

/* id가 2인 행 삭제 */
delete from YsoftmanTable where id=2

/* 테이블 삭제 */
drop table "YsoftmanTable"



[MySQL 을 -> NoSQL 처럼]
-TPS(Transation Per Second) 성능의 대부부능 DataBase 층이 아닌 SQL 층에서 발생
 : MySQL 의 대부분의 오버헤드는 SQL 을 파싱하고 처리하는데 있고, InnoDB 접근하는 시간은 그리 길지 않다.
-InnoDB 에 접근할 수 있도록 해주는 HandlerSocket를 사용하여 NoSQL 로 접근(SQL과 NoSQL 로 동시 접근 가능)
-벤치마크 결과 750,000 QPS(Query Per Second) 처리
-참고
 원문 : http://yoshinorimatsunobu.blogspot.com/2010/10/using-mysql-as-nosql-story-for.html
 한글 : http://note.oiko.cc/post/2937725236/handlersocket-for-mysql

SQL Query Browser

[free SQL Query Browser]
Oracle SQL Developer http://www.oracle.com/technetwork/developer-tools/sql-developer/overview/index.html
MySQL WorkBench http://www.mysql.com/downloads/workbench/
MySQL(sqlite, oracle, mssql, postgresql...) dbeaver https://dbeaver.io/
MySQL SQLyog http://www.webyog.com/
MySQL HeidiSQL http://www.heidisql.com/ (추천)
MSSQL SSMS(SQL Server Management Studio) http://www.microsoft.com/en-us/download/details.aspx?id=7593

ARM 계열 맥북 M1 등에서 mysql workbench 최신 버전(8.0.x)이 계속 크래시 되는 이슈가 있다.

대신 dbeaver 를 사용하자.
brew install --cask dbeaver-community

ctrl+enter : 쿼리 하나 실행
ctrl+\ : 현재탭의 모든 쿼리 실행
ctrl+/ : 현재 라인 주석 토글
ctrl+shift+F : 쿼리 포맷팅
alt+up : 이전 쿼리 위치로 이동
alt+down : 다음 쿼리 위치로 이동
ctrl+shift+j : 라인 합치기
ctrl+shift+\ : 실행 결과 창 닫기
cmd+shift-x : to uppercaes
cmd+shift-y : to lowercase

sql query examples

-- show command 로 정보 확인
show databases;
show tables;
show variables;
show processlist;
show variables like 'log_output%';
show variables like '%timeout%';

-- db 선택
use ysoftman;

-- create
create table `test_info` (
`id` bigint(20) unsigned not null auto_increment,
`age` int(11) default null,
`name` varchar(45) default null,
`enable` tinyint(1) default 1,
`created_at` datetime default current_timestamp,
`updated_at` datetime default current_timestamp,
`deleted_at` datetime default current_timestamp,
`last_date` datetime default null,
primary key (`id`)
) engine=innodb default charset=utf8;

-- select
select * from user;
select * from user limit 10;
select * from user where name like '%ysoftman%' or name like '%bill%';
select * from user order by id;

-- update
update ysoftman.user set nickname = 'xelloss' where name = 'bill';
update ysoftman.user set nickname = 'xelloss' where name in ('bill', 'yoon', 'naruto');

-- 3개의 테이블 left, right join
select
svc1.name as svc1_name,
svc1.description as svc1_desc,
ifnull(svc2.aaa, '') as svc2_aaa,
ifnull(svc3.aaa, '') as svc3_aaa,
from service1 svc1
right join service2 svc2 on svc1.service2_id=svc2.id
left join service3 svc3 on svc1.service3_id=svc3.id
where s.name='bill' order by name asc;

-- major, minor 별 path 가장 높은 버전으로 조회
select * from version_dha_resource as t1
join (
select
  version_major,
    version_minor,
  max(version_patch) as patch
from version_dha_resource
group by version_major, version_minor
) as t2 on t1.version_major = t2.version_major and t1.version_minor = t2.version_minor and t1.version_patch = t2.patch;

/*
mssql 저장 프로시져 테스트
*/
use [TestSP]
create proc SPQuery(
@a varchar(20),
@b varchar(20),
@c int,
@d float,
@e bigint,
@f int)
as
declare @idx int;
set @idx = 0;
while (@idx < 10)
begin
insert into mytable(col1, col2, col3, col4, col5, col6) values(@a, @b, @c, @d, @e, @f)
set @idx = @idx + 1
end

/*
저장 프로시져 실행
*/
exec SPQuery 'ysoftman', yoon, 123, 1.0, 12345, 123

MSSQL 계정 암호 변경하기

MSSQL 에서 sa 나 기타 로그인 아이디에 대한 패스워드를 잊어 버렸다면 아래와 같이 재설정 할 수 있다.
cmd 콘솔에서 sqlcmd 을 실행한다. (참고로 :help 하면 도움말이 표시된다.)
1> alter login ysoftman with password="abc123";
2> go
3> exit

MS SQL XML 데이터 저장

[Microsoft SQL XML 데이터 타입]
-XML 형식으로 데이터를 지원, XML 형식의 데이터를 찾고, 입력하고, 수정하고, 삭제 가능
-SQL Server 2000 이후 부터 지원
-XML 데이터는 내부적으로 Binary로 저장되며 일반적인 경우 약간의 압축이 제공되어 인스턴스당 2GB 저장 가능
-참고
 http://technet.microsoft.com/ko-kr/library/ms177454.aspx
-예제
/*
테이블 생성 시 XML 형식의 열을 포함하도록 한다.
XML 키워드로 만든 xmldata 로 여러가지 쿼리를 수행한다.
*/
create table YsoftmanTable(id int not null, xmldata xml)
/* id가 1인 행에 XML 형식의 데이터 입력하기 */
insert into YsoftmanTable select 1, '
<?Employee Info?>
<Employee>
 <Name>YoonByoungHoon</Name>
 <Sex>Male</Sex>
 <Phone>123456789</Phone>
</Employee>
'
/* id가 2인 행에 XML 형식의 데이터 입력하기 */
insert into YsoftmanTable select 2, '
<?Employee Info?>
<Employee>
 <Name>BillGates</Name>
 <Sex>Male</Sex>
 <Phone>55555</Phone>
</Employee>
'
/* 내용 확인 */
select * from YsoftmanTable
/* id가 2인 행에서 Employee 하위 요소인 Name 요소의 모든 내용 찾기 */
select xmldata.query('/Employee/Name') from YsoftmanTable where id=2
/* id가 2인 행에서 Employee 하위에 Address 요소를 첫번째 위치로 추가 */
update YsoftmanTable set xmldata.modify('insert <Address>Seattle</Address> as first into (/Employee)[1]') where id=2
/* id가 2인 행에서 Employee 하위에 Mobile 요소를 Phone 요소 앞에 추가 */
update YsoftmanTable set xmldata.modify('insert <Mobile>2222</Mobile> before (/Employee/Phone)[1]') where id=2
/* id가 2인 행에서 Employee 하위에 Mobile 요소의 값을 변경 */
update YsoftmanTable set xmldata.modify('replace value of (/Employee/Mobile/text())[1] with "333"') where id=2
/* id가 2인 행에서 Employee 하위 요소인 Name 요소의 모든 내용 삭제 */
update YsoftmanTable set xmldata.modify('delete /Employee/Name') where id=2
/* id가 2인 행 삭제 */
delete from YsoftmanTable where id=2
/* 테이블 삭제 */
drop table "YsoftmanTable"