safe_mysqld -Sg &

또는

safe_mysqld --skip-grant &

(skip grant table)

 

'DB' 카테고리의 다른 글

RAC 구축  (0) 2008.03.06
오라클 테이블 내용 복구하기  (0) 2008.02.18
mysql  (0) 2007.11.09
mysql 로그가 차면??  (0) 2007.10.20
mysql에서 버젼보기  (0) 2007.10.19
Posted by '김용환'
,

mysql

DB 2007. 11. 9. 21:04

mysqladmin variables -uroot -p

 

mysqladmin status extended-status -uroot -p

 

mysqladmin -i3 processlist -uroot -p

 

Aborted_clients : 클라이언트에서 연결을 적절하게 닫지 못하고 죽어서 취소된 연결 횟수
Aborted_connects : 연결 시도 실패 횟수
Connections : mysql 서버에 연결 시도한 횟수
Key_blocks_used : 키 캐쉬에서 사용된 블락 횟수
Key_read_requests : 캐쉬에서 키 블락을 읽어들인 요청 횟수
Key_reads : 디스크에서 물리적으로 키 블락을 읽어들인 횟수
Max_used_connections : 최대 동시 접속자수
Open_tables : 현재 열린 테이블 숫자
Open_files : 현재 연 파일 숫자
Opened_tables : 열었던 테이블 숫자
Select_full_join : 인덱스를 사용하지 않은 조인
Questions : 서버로 보낸 질의 횟수
Slow_queries : long_query_time 이상 넘어간 질의 횟수
Sort_merge_passes : 정렬을 위해 병합한 숫자
Table_locks_waited : 테이블 락을 위해 대기한 시간

 

 

Uptime: 6770803  Threads: 250  Questions: 105616370  Slow queries: 1538  Opens: 1762  Flush tables: 1  Open tables: 82  Queries per second avg: 15.599
+--------------------------+------------+
| Variable_name            | Value      |
+--------------------------+------------+
| Aborted_clients          | 1491446    |
| Aborted_connects         | 154        |
| Binlog_cache_disk_use    | 0          |
| Binlog_cache_use         | 0          |
| Bytes_received           | 2002528374 |
| Bytes_sent               | 55227217   |
| Com_admin_commands       | 22569      |
| Com_alter_db             | 0          |
| Com_alter_table          | 156        |
| Com_analyze              | 0          |
| Com_backup_table         | 0          |
| Com_begin                | 0          |
| Com_change_db            | 567044     |
| Com_change_master        | 0          |
| Com_check                | 3          |
| Com_checksum             | 0          |
| Com_commit               | 28090017   |
| Com_create_db            | 0          |
| Com_create_function      | 0          |
| Com_create_index         | 0          |
| Com_create_table         | 156        |
| Com_dealloc_sql          | 0          |
| Com_delete               | 3558965    |
| Com_delete_multi         | 0          |
| Com_do                   | 0          |
| Com_drop_db              | 0          |
| Com_drop_function        | 0          |
| Com_drop_index           | 0          |
| Com_drop_table           | 156        |
| Com_drop_user            | 0          |
| Com_execute_sql          | 0          |
| Com_flush                | 0          |
| Com_grant                | 0          |
| Com_ha_close             | 0          |
| Com_ha_open              | 0          |
| Com_ha_read              | 0          |
| Com_help                 | 0          |
| Com_insert               | 26744030   |
| Com_insert_select        | 312        |
| Com_kill                 | 0          |
| Com_load                 | 0          |
| Com_load_master_data     | 0          |
| Com_load_master_table    | 0          |
| Com_lock_tables          | 158        |
| Com_optimize             | 0          |
| Com_preload_keys         | 0          |
| Com_prepare_sql          | 0          |
| Com_purge                | 33         |
| Com_purge_before_date    | 0          |
| Com_rename_table         | 0          |
| Com_repair               | 0          |
| Com_replace              | 0          |
| Com_replace_select       | 0          |
| Com_reset                | 0          |
| Com_restore_table        | 0          |
| Com_revoke               | 0          |
| Com_revoke_all           | 0          |
| Com_rollback             | 5262306    |
| Com_savepoint            | 0          |
| Com_select               | 14570453   |
| Com_set_option           | 17998640   |
| Com_show_binlog_events   | 0          |
| Com_show_binlogs         | 122        |
| Com_show_charsets        | 0          |
| Com_show_collations      | 746165     |
| Com_show_column_types    | 0          |
| Com_show_create_db       | 158        |
| Com_show_create_table    | 4035       |
| Com_show_databases       | 24         |
| Com_show_errors          | 0          |
| Com_show_fields          | 4278       |
| Com_show_grants          | 0          |
| Com_show_innodb_status   | 734        |
| Com_show_keys            | 0          |
| Com_show_logs            | 0          |
| Com_show_master_status   | 0          |
| Com_show_new_master      | 0          |
| Com_show_open_tables     | 0          |
| Com_show_privileges      | 0          |
| Com_show_processlist     | 15         |
| Com_show_slave_hosts     | 0          |
| Com_show_slave_status    | 0          |
| Com_show_status          | 45888      |
| Com_show_storage_engines | 0          |
| Com_show_tables          | 223        |
| Com_show_variables       | 768747     |
| Com_show_warnings        | 791        |
| Com_slave_start          | 0          |
| Com_slave_stop           | 0          |
| Com_truncate             | 1          |
| Com_unlock_tables        | 158        |
| Com_update               | 3459497    |
| Com_update_multi         | 0          |
| Connections              | 836958     |
| Created_tmp_disk_tables  | 7110       |
| Created_tmp_files        | 373        |
| Created_tmp_tables       | 56034      |
| Delayed_errors           | 0          |
| Delayed_insert_threads   | 0          |
| Delayed_writes           | 0          |
| Flush_commands           | 1          |
| Handler_commit           | 158        |
| Handler_delete           | 2793309    |
| Handler_discover         | 0          |
| Handler_read_first       | 938        |
| Handler_read_key         | 15018787   |
| Handler_read_next        | 102283727  |
| Handler_read_prev        | 14941879   |
| Handler_read_rnd         | 13161303   |
| Handler_read_rnd_next    | 1375783201 |
| Handler_rollback         | 91         |
| Handler_update           | 13545343   |
| Handler_write            | 36151275   |
| Key_blocks_not_flushed   | 0          |
| Key_blocks_unused        | 90983      |
| Key_blocks_used          | 348900     |
| Key_read_requests        | 710311501  |
| Key_reads                | 4751132    |
| Key_write_requests       | 171022496  |
| Key_writes               | 160786547  |
| Max_used_connections     | 1519       |
| Not_flushed_delayed_rows | 0          |
| Open_files               | 139        |
| Open_streams             | 0          |
| Open_tables              | 82         |
| Opened_tables            | 1762       |
| Qcache_free_blocks       | 421        |
| Qcache_free_memory       | 22463472   |
| Qcache_hits              | 3592193    |
| Qcache_inserts           | 5013407    |
| Qcache_lowmem_prunes     | 0          |
| Qcache_not_cached        | 9584148    |
| Qcache_queries_in_cache  | 2532       |
| Qcache_total_blocks      | 5653       |
| Questions                | 105616370  |
| Rpl_status               | NULL       |
| Select_full_join         | 0          |
| Select_full_range_join   | 0          |
| Select_range             | 22517      |
| Select_range_check       | 0          |
| Select_scan              | 3016542    |
| Slave_open_temp_tables   | 0          |
| Slave_running            | OFF        |
| Slow_launch_threads      | 0          |
| Slow_queries             | 1538       |
| Sort_merge_passes        | 203        |
| Sort_range               | 1523       |
| Sort_rows                | 3865615    |
| Sort_scan                | 56011      |
| Table_locks_immediate    | 42239400   |
| Table_locks_waited       | 1071912    |
| Threads_cached           | 0          |
| Threads_connected        | 250        |
| Threads_created          | 270157     |
| Threads_running          | 1          |
| Uptime                   | 6770803    |
+--------------------------+------------+

 

 

+---------------------------------+----------------------------------------+
| Variable_name                   | Value                                  |
+---------------------------------+----------------------------------------+
| back_log                        | 50                                     |
| basedir                         | /usr/local/mysql/                      |
| binlog_cache_size               | 32768                                  |
| bulk_insert_buffer_size         | 8388608                                |
| character_set_client            | euckr                                  |
| character_set_connection        | euckr                                  |
| character_set_database          | euckr                                  |
| character_set_results           | euckr                                  |
| character_set_server            | euckr                                  |
| character_set_system            | utf8                                   |
| character_sets_dir              | /usr/local/mysql/share/mysql/charsets/ |
| collation_connection            | euckr_korean_ci                        |
| collation_database              | euckr_korean_ci                        |
| collation_server                | euckr_korean_ci                        |
| concurrent_insert               | ON                                     |
| connect_timeout                 | 5                                      |
| datadir                         | /usr/local/mysql/var/                  |
| date_format                     | %Y-%m-%d                               |
| datetime_format                 | %Y-%m-%d %H:%i:%s                      |
| default_week_format             | 0                                      |
| delay_key_write                 | ON                                     |
| delayed_insert_limit            | 100                                    |
| delayed_insert_timeout          | 300                                    |
| delayed_queue_size              | 1000                                   |
| expire_logs_days                | 0                                      |
| flush                           | OFF                                    |
| flush_time                      | 0                                      |
| ft_boolean_syntax               | + -><()~*:""&|                         |
| ft_max_word_len                 | 84                                     |
| ft_min_word_len                 | 4                                      |
| ft_query_expansion_limit        | 20                                     |
| ft_stopword_file                | (built-in)                             |
| group_concat_max_len            | 1024                                   |
| have_archive                    | NO                                     |
| have_bdb                        | NO                                     |
| have_compress                   | YES                                    |
| have_crypt                      | YES                                    |
| have_csv                        | NO                                     |
| have_example_engine             | NO                                     |
| have_geometry                   | YES                                    |
| have_innodb                     | YES                                    |
| have_isam                       | NO                                     |
| have_ndbcluster                 | NO                                     |
| have_openssl                    | NO                                     |
| have_query_cache                | YES                                    |
| have_raid                       | NO                                     |
| have_rtree_keys                 | YES                                    |
| have_symlink                    | YES                                    |
| init_connect                    |                                        |
| init_file                       |                                        |
| init_slave                      |                                        |
| innodb_additional_mem_pool_size | 1048576                                |
| innodb_autoextend_increment     | 8                                      |
| innodb_buffer_pool_awe_mem_mb   | 0                                      |
| innodb_buffer_pool_size         | 8388608                                |
| innodb_data_file_path           | ibdata1:10M:autoextend                 |
| innodb_data_home_dir            |                                        |
| innodb_fast_shutdown            | ON                                     |
| innodb_file_io_threads          | 4                                      |
| innodb_file_per_table           | OFF                                    |
| innodb_flush_log_at_trx_commit  | 1                                      |
| innodb_flush_method             |                                        |
| innodb_force_recovery           | 0                                      |
| innodb_lock_wait_timeout        | 50                                     |
| innodb_locks_unsafe_for_binlog  | OFF                                    |
| innodb_log_arch_dir             |                                        |
| innodb_log_archive              | OFF                                    |
| innodb_log_buffer_size          | 1048576                                |
| innodb_log_file_size            | 5242880                                |
| innodb_log_files_in_group       | 2                                      |
| innodb_log_group_home_dir       | ./                                     |
| innodb_max_dirty_pages_pct      | 90                                     |
| innodb_max_purge_lag            | 0                                      |
| innodb_mirrored_log_groups      | 1                                      |
| innodb_open_files               | 300                                    |
| innodb_table_locks              | ON                                     |
| innodb_thread_concurrency       | 8                                      |
| interactive_timeout             | 1800000                                |
| join_buffer_size                | 131072                                 |
| key_buffer_size                 | 402653184                              |
| key_cache_age_threshold         | 300                                    |
| key_cache_block_size            | 1024                                   |
| key_cache_division_limit        | 100                                    |
| language                        | /usr/local/mysql/share/mysql/english/  |
| large_files_support             | ON                                     |
| license                         | GPL                                    |
| local_infile                    | ON                                     |
| locked_in_memory                | OFF                                    |
| log                             | OFF                                    |
| log_bin                         | ON                                     |
| log_error                       |                                        |
| log_slave_updates               | OFF                                    |
| log_slow_queries                | ON                                     |
| log_update                      | OFF                                    |
| log_warnings                    | 1                                      |
| long_query_time                 | 3                                      |
| low_priority_updates            | OFF                                    |
| lower_case_file_system          | OFF                                    |
| lower_case_table_names          | 0                                      |
| max_allowed_packet              | 10484736                               |
| max_binlog_cache_size           | 4294967295                             |
| max_binlog_size                 | 1073741824                             |
| max_connect_errors              | 99999999                               |
| max_connections                 | 2000                                   |
| max_delayed_threads             | 20                                     |
| max_error_count                 | 64                                     |
| max_heap_table_size             | 16777216                               |
| max_insert_delayed_threads      | 20                                     |
| max_join_size                   | 4294967295                             |
| max_length_for_sort_data        | 1024                                   |
| max_relay_log_size              | 0                                      |
| max_seeks_for_key               | 4294967295                             |
| max_sort_length                 | 1024                                   |
| max_tmp_tables                  | 32                                     |
| max_user_connections            | 0                                      |
| max_write_lock_count            | 4294967295                             |
| myisam_data_pointer_size        | 4                                      |
| myisam_max_extra_sort_file_size | 2147483648                             |
| myisam_max_sort_file_size       | 2147483647                             |
| myisam_recover_options          | OFF                                    |
| myisam_repair_threads           | 1                                      |
| myisam_sort_buffer_size         | 67108864                               |
| net_buffer_length               | 16384                                  |
| net_read_timeout                | 30                                     |
| net_retry_count                 | 10                                     |
| net_write_timeout               | 60                                     |
| new                             | OFF                                    |
| old_passwords                   | OFF                                    |
| open_files_limit                | 16000                                  |
| pid_file                        | /usr/local/mysql/var/ssss.pid        |
| port                            | 3306                                   |
| preload_buffer_size             | 32768                                  |
| protocol_version                | 10                                     |
| query_alloc_block_size          | 8192                                   |
| query_cache_limit               | 1048576                                |
| query_cache_min_res_unit        | 4096                                   |
| query_cache_size                | 33554432                               |
| query_cache_type                | ON                                     |
| query_cache_wlock_invalidate    | OFF                                    |
| query_prealloc_size             | 8192                                   |
| range_alloc_block_size          | 2048                                   |
| read_buffer_size                | 258048                                 |
| read_only                       | OFF                                    |
| read_rnd_buffer_size            | 262144                                 |
| relay_log_purge                 | ON                                     |
| rpl_recovery_rank               | 0                                      |
| secure_auth                     | OFF                                    |
| server_id                       | 1                                      |
| skip_external_locking           | ON                                     |
| skip_networking                 | OFF                                    |
| skip_show_database              | OFF                                    |
| slave_net_timeout               | 3600                                   |
| slow_launch_time                | 2                                      |
| socket                          | /tmp/mysql.sock                        |
| sort_buffer_size                | 262136                                 |
| sql_mode                        |                                        |
| storage_engine                  | MyISAM                                 |
| sync_binlog                     | 0                                      |
| sync_replication                | 0                                      |
| sync_replication_slave_id       | 0                                      |
| sync_replication_timeout        | 0                                      |
| sync_frm                        | ON                                     |
| system_time_zone                | KST                                    |
| table_cache                     | 512                                    |
| table_type                      | MyISAM                                 |
| thread_cache_size               | 8                                      |
| thread_stack                    | 196608                                 |
| time_format                     | %H:%i:%s                               |
| time_zone                       | SYSTEM                                 |
| tmp_table_size                  | 33554432                               |
| tmpdir                          |                                        |
| transaction_alloc_block_size    | 8192                                   |
| transaction_prealloc_size       | 4096                                   |
| tx_isolation                    | REPEATABLE-READ                        |
| version                         | 4.1.10-log                             |
| version_comment                 | Source distribution                    |
| version_compile_machine         | i686                                   |
| version_compile_os              | pc-linux-gnu                           |
| wait_timeout                    | 1800000                                |
+---------------------------------+----------------------------------------+

'DB' 카테고리의 다른 글

오라클 테이블 내용 복구하기  (0) 2008.02.18
mysql 에서 root 암호 잃어버렸을 때  (0) 2007.12.31
mysql 로그가 차면??  (0) 2007.10.20
mysql에서 버젼보기  (0) 2007.10.19
ERR=12505 에러  (1) 2007.10.11
Posted by '김용환'
,

mysql 로그가 차면??

DB 2007. 10. 20. 00:33

mysql 로그가 꽉 차면 어떤 일이 벌어질까?

 

우선 mysql 서버의 부하량이 엄청나게 늘어나면서 로드량이 커진다.

 

해당 테이블 파일을

 

rm 테이블이름.MYD

cp /dev/null 테이블 이름.MYD

 

를 사용해서는 안된다.

 

그냥 지우면,

--- Cause: java.sql.SQLException: General error,  message from server: "Got error 127 from storage engine"

 

이런 에러가 나면, 결국은 복구해야 하는데, 어렵다.

 

 

차라리. mysql 에 직접들어가 다음과 같이 사용하도록 하라~

 

truncate 테이블 이름;

 

 

'DB' 카테고리의 다른 글

mysql 에서 root 암호 잃어버렸을 때  (0) 2007.12.31
mysql  (0) 2007.11.09
mysql에서 버젼보기  (0) 2007.10.19
ERR=12505 에러  (1) 2007.10.11
ibatis에서 map 사용하기.  (0) 2007.10.03
Posted by '김용환'
,

mysql에서 버젼보기

DB 2007. 10. 19. 00:16
mysql> select version();
+------------+
| version()  |
+------------+
| 4.1.12-log |
+------------+
1 row in set (0.00 sec)wiki

'DB' 카테고리의 다른 글

mysql  (0) 2007.11.09
mysql 로그가 차면??  (0) 2007.10.20
ERR=12505 에러  (1) 2007.10.11
ibatis에서 map 사용하기.  (0) 2007.10.03
delete, truncate, drop의 차이점  (0) 2007.09.27
Posted by '김용환'
,

ERR=12505 에러

DB 2007. 10. 11. 04:36

 

DB 연결이 안되는 장애가 생겼다.

 

Caused by: java.sql.SQLException: IO 예외 상황:  Connection refused(DESCRIPTION=(TMP=)(VSNNUM=153094144)(ERR=12505)(ERROR_STACK=(ERROR=(CODE=12505)(EMFI=4))))

 

 

원인은 ERR=12505 였다.

 

하지만, 이와 함께 여러 Exception이 발견되었다. 이 것만 봤었으면 인증문제인줄로 생각할 수도 있겠지만, 그보다 더 근본원인을 찾아야 한다.

 

java.lang.RuntimeException: Cannot create DataSource jdbc:oracle:thin:@1111.1.24:1606:google
org.apache.commons.dbcp.SQLNestedException: Cannot create PoolableConnectionFactory (ORA-01017: invalid username/password; logon denied

 

 

12505, 00000, "TNS:listener could not resolve SID given in connect descriptor"
// *Cause:  The SID in the CONNECT_DATA was not found in the listener's tables.
// *Action: Check to make sure that the SID specified is correct.
// The SIDs that are currently registered with the listener can be obtained by
// typing "LSNRCTL SERVICES ".  These SIDs correspond to SID_NAMEs
// in TNSNAMES.ORA, or db_names in INIT.ORA.
// *Comment: This error will be returned if the database instance has not
// registered with the listener; the instance may need to be started.

 

원인은 다음과 같다. 오라클 SID가 자바클라이언트와 오라클 서버간의 SID가 서로 다르기 때문이다.

 

ORA9로 변경하니 SID가 서로 맞아서 문제 해결이 되었다..

 

DBA에게 sid를 확인해 달라고 한다.

다음의 명령어를 오라클 서버에서 해달라고 부탁한다.

ps -ef |  grep smon

 

Posted by '김용환'
,

ibatis에서 map 사용하기.

DB 2007. 10. 3. 02:50

ibatis에서 다들 list를 쓰고 있는데, map도 지원된다.

queryForMap() 메소드를 활용하면 Map을 리턴한다.

 

 

 

 

출처:

http://opensource.atlassian.com/confluence/oss/display/IBATIS/How+do+I+get+a+Map+of+results+instead+of+a+List

 

The following section will explain in detail how to use the queryForMap().

The queryForMap()'s are most useful when you need to work with the result of a query. In the example below I will use a query that return Student objects as a result. Lets start with the Student class.

Student.java
public class Student implements java.io.Serializable {

private String id, firstName, lastName;

public String getId() {
    return id;
}

public void setId(String id) {
    this.id = id;
}

public String getFirstName() {
    return firstName;
}

public void setFirstName(String firstName) {
    this.firstName = firstName;
}

public String getLastName() {
    return lastName;
}

public void setLastName(String lastName) {
    this.lastName = lastName;
}

And now the SqlMap ....

<resultMap id="studentResult" class="com.domain.Student">
    <result column="id" property="id" />
    <result column="first_name" property="firstName" />
    <result column="last_name" property="lastName" />
</resultMap>

<select id="getAllStudents" resultMap="studentResult">
select
    *
from students
</select>

Now that the basics are out of the way query away!

Lets say that you need to do some fast serching on the returned students. The best way is to have a Map of the Student objects to their id's.

This is where the queryForMap() comes into play. There are two different options and both will be dicussed. The first is perfect for the example given above.

public Map getAllStudents() {

    Map<String, Student> studentsMap = queryForMap("getAllStudents", null, "id");

    Student student = studentsMap.get("123456");
    
    ...
}

You can see that the third parameter in the call looks for the property "id" in the result map and then creates the map with that property as the key.

The second option allow you to specify both the key and the value.

Map<String, String> studentsMap = queryForMap("getAllStudents", null, "id", "firstName");

The above code will return a Map with the id as the key and the firstName as the value.

There are many other uses for these method so feel free to add them on

 

 

Posted by '김용환'
,

 

제일 잘 나온 내용이라 발췌~

 

 

출처

http://www.okjsp.pe.kr/seq/2035

 

delete,truncate,drop문의 비교.
DELETE, DROP, TRUNCATE의 비교
----------------------------------------------------------------

TABLE에서 행을 삭제하는 세 가지 OPTION의 비교

TABLE에서 모든 행을 삭제하는 방법에는 다음과 같은 세 가지 OPTION이 있다.

1. DELETE 명령어 사용

DELETE 명령어를 사용하여 TABLE의 행을 삭제할 수 있다.
예를 들어 EMP TABLE에서 모든 행을 삭제하는 명령문은 다음과 같다.

DELETE FROM emp;

O. DELETE 문을 사용할 때 TABLE이나 CLUSTER에 행이 많으면 행이 삭제 될 때마다 많은 SYSTEM 자원이 소모된다. 예를 들어 CPU 시간,REDO LOG 영역, TABLE이나 INDEX에 대한 ROLLBACK SEGMENT 영역 등의 자원이 필요하다.
O. TRIGGER가 걸려있다면 각 행이 삭제될 때 실행된다.
O. 이전에 할당되었던 영역은 삭제되어 빈 TABLE이나 CLUSTER에 그대로 남아 있게 된다.

2. DROP 과 CREATE 명령어 사용

TABLE을 삭제한 다음 재생성할 수 있다. 예를 들어 EMP TABLE을 삭제하고 재생성하는 명령문은 다음과 같다.

DROP TABLE emp;
CREATE TABLE emp (......);

O. TABLE이나 CLUSTER를 삭제하고 재생성하면 모든 관련된 INDEX, CONSTRAINT,TRIGGER도 삭제되며, 삭제된 TABLE이나 CLUSTERED TABLE에 종속된 OBJECTS는 무효화 된다.
O. 삭제된 TABLE이나 CLUSTERED TABLE에 부여된 권한도 삭제된다.

3. TRUNCATE 명령어 사용

SQL명령어 TRUNCATE를 사용하여 TABLE의 모든 행을 삭제할 수 있다.
예를 들어 EMP TABLE을 잘라내는 명령문은 다음과 같다.

TRUNCATE TABLE emp:

O. TRUNCATE 명령어는 TABLE이나 CLUSTER에서 모든 행을 삭제하는 빠르고 효율적인 방법이다.
O. TRUNCATE 명령어는 어떤 ROLLBACK 정보도 만들지 않고 즉시 COMMIT한다.
O. TRUNCATE 명령어는 DDL 명령문으로 ROLLBACK될 수 없다.
O. TRUNCATE 명령문은 잘라 버릴 TABLE과 관련된 구조(CONSTRAINT, TRIGGER 등)과 권한에 영향을 주지 않는다.
O. TRUNCATE 명령문은 현재 TABLE에 할당된 영역을 잘라버린 후에 포함되는 TABLESPACE로 복귀되도록 지정한다.
(REUSE STORAGE, DROP STORAGE OPTION 사용)
- DROP STORAGE OPTION 사용 시 : TABLE EXTENTS 수를 MINEXTENTS의 원래 설정값으로 줄인다.
해제된 확장영역은 SYSTEM에 복귀되며, 다른 OBJECTS가 사용할 수 있다.
- REUSE STORAGE OPTION 사용 시 : 현재 TABLE이나 CLUSTER에 할당된 모든 영역이 할당된 채로 남아 있도록 지정한다.
O. TRUNCATE 명령문이 TABLE에서 ROW를 삭제하면 해당 TABLE에 걸려 있는 TRIGGER는 실행되지 않는다.

O. AUDIT 기능이 ENABLE되어 있으면, TRUNCATE 명령문은 DELETE문에 해당하는 AUDIT 정보를 생성하지 않는다. 대신 발생한 TRUNCATE 명령문에 대한 단일 AUDIT RECORD를 생성한다.

* HASH CLUSTER는 잘라버릴 수 없다.

또한 HASH CLUSTER나 INDEX CLUSTER 내의 TABLE도 개별적으로 잘라버릴 수 없다.
INDEX CLUSTER를 잘라버리면 CLUSTER에 있는 모든 TABLE의 모든 ROW가 삭제된다.
모든 ROW가 각각의 CLUSTERED TABLE에서 삭제되어야 한다면 DELETE 명령어를 사용하거나 TABLE을 삭제하고 재생성한다.

from koug

laalaal~

Posted by '김용환'
,

* 허접 구닥다리 wono의 Linux에서 JSP 시작하기 3.

(IBatis 사용하기)

 

원본 글 사이트는 아래와 같습니다.

 

http://blog.naver.com/wono77/140030004047

 

* 글쓴 History:

최초 글쓴시각- 2006년 10월 20일.

수정- 2006년 10월 27일.

이번엔 DB를 접근할 차례입니다.

 

(제 강좌는 Linux 콘솔에서 직접 java 명령어로 컴파일합니다.

DB는 mysql 사용.

일단은 윈도우와 요즘 인기있는 자바툴인 이클립스를 쓰지 않습니다.

초보가 구조적으로 디렉토리 구조등을 이해하기 위해서 리눅스 콘솔이 더 좋다고 생각하기 때문입니다.

3번 강좌를 보시기전에 1,2번 강좌를 선행하시기 바랍니다.^^)

 

먼저 IBatis를 프레임웍 기반이 아닌,

처음부터 초보가... mysql db를 생쿼리로 날리는 것 밖에 모르는 ..

log4j, struts, spring을 모르는 정말 초보가 IBatis로 SqlMap을 어떻게 접근해나가야할까..

저는 그런 고민을 하였으며,

iBatis를 시작하는 많은 사람들이 고민하였을 문제일것입니다.

 

그러나, 인터넷에는 그런 한글 문서를 찾기가 힘들더군요.

구전으로 전해지는것일까요? (아마, 그런것 같습니다.)

아니면, 좋은 출판된 책이라도 있는 것일까요? (이건 아직 아닌것 같습니다^^)

 

IBatis를 어떻게 어디서 다운받아서 어디에 설치하고, 설정은 어떻게 하라는

초보적인 문서가 없었습니다.

 

그래서 직접 설치하면서 하나하나 정리해 보았습니다.

 

여기서 일단 집고 넘어가보지요.

 

IBatis 가 무엇입니까?

 

DB를 xml 형식으로 좀더 효율적으로 사용하자는 것입니다.

java 파일에서 db를 사용할때, xml에 따로 빼서 사용하자는 건데...

 

hibernate란 것도 있습니다.

이 IBatis란 것을 spring+Ibatis, struts+Ibatis로 쓰기도 하고, log4j+Ibatis로도 쓰기도 합니다.

 

http://ibatis.apache.org/javadownloads.html

일단 위 사이트에서 iBatis를 다운로드 받으세요.

 

바이너리 판이라서 설치하실 필요가 없습니다.

윈도우에 일단 받아서 압축을 풀어보시면,

저 파일중 필요한 폴더는 lib 단 1개입니다.

 

lib안에 3개의 jar파일이 있는데요, 실제 필요한 것은 2개입니다.

 

ibatis2-common-2.1.6.589.jar

ibatis2-sqlmap-2.1.6.589.jar

 

사용하는 jar 파일들은 일단 톰캣에서 공통적으로 사용하는 common에 밀어 넣도록 하겠습니다.

 

/apache-tomcat/common/lib

위 폴더 아래에 2파일을 밀어 넣는다.

 

그리고 사용하기 위한 설정에 대한 설명이 "이동국"님이 작성하신 메뉴얼이 역시 위 링크에 있습니다.

허락은 감히 받지 않았지만, 그 pdf 메뉴얼을 여기 올립니다.

문서가 2개인데 하나는 용량이 5메가라 안올라가네요..

 

lib에 파일을 밀어 넣었는데, 윈도우, 리눅스 모두 이 lib 디렉토리의 classpath를 잡아주어야합니다.

 

저는 리눅스 bash 쉘을 쓰므로, .bash_profile 을 아래와 같이 설정합니다.

저는 자바를 /home/wono/jsp/jdk 에 설치했으며,

톰캣은 /home/wono/jsp/local/apache-tomcat 에 설치했습니다.

 

# .bash_profile

# Get the aliases and functions
if [ -f ~/.bashrc ]; then
    . ~/.bashrc
fi

# User specific environment and startup programs

SVN_EDITOR=/usr/bin/vim
export SVN_EDITOR

IRTEAM=/home/wono

PATH=$PATH:$HOME/bin:/usr/local/bin:

export PATH
unset USERNAME

#자바 설정

JAVA_HOME=/home/wono/jsp/jdk
CATALINA_HOME=/home/wono/jsp/local/apache-tomcat
PATH=$JAVA_HOME/bin:$CATALINA_HOME/bin:$PATH
export JAVA_HOME CATALINA_HOME
#export CLASSPATH="$CATALINA_HOME/common/lib/servlet-api.jar:$JAVA_HOME/mysql-connector-java-5.0.2-beta-bin.jar:."
export CLASSPATH="$CATALINA_HOME/common/lib/servlet-api.jar:$JAVA_HOME/mysql-connector-java-5.0.2-beta-bin.jar:$CATALINA_HOME/common/lib/jsp-api.jar"
export CLASSPATH="$CLASSPATH:$CATALINA_HOME/common/lib:$CATALINA_HOME/common/lib/*.jar:$CATALINA_HOME/common/lib/ibatis2-common-2.1.6.589.jar:$CATALINA_HOME/common/lib/ibatis2-sqlmap-2.1.6.589.jar:."
#export CLASSPATH="$CLASSPATH:$CATALINA_HOME/common/lib/jsp-api.jar"
#--------------------------------------------------------------
# myapp
# myapp의 lib추가
#export CLASSPATH="$CATALINA_HOME/webapps/myapp/WEB-INF/lib:$CATALINA_HOME/webapps/myapp/WEB-INF/lib/*.jar"
export CLASSPATH="$CLASSPATH:$CATALINA_HOME/webapps/myapp/WEB-INF/classes:$CATALINA_HOME/webapps/myapp/WEB-INF/classes/*.xml:$CATALINA_HOME/webapps/myapp/WEB-INF/classes/*.properties"

export PATH

 

source .bashrc를 해주거나, 재접을 하시고, 1번 강좌에서 설명한

myapp라는 폴더에서 작업을 하겠습니다.

 

제가 iBatis로 해볼 작업은 다음과 같습니다.

 

Mysql의 DB명 testDB

Table 이름과 속성은 아래와 같습니다.

tb_Person{

int pid,

varchar pname 

}
 

안에 값을 간단히 넣어 두세요.^^

insert into tb_Person values(2222,'wono');

insert into tb_Person values(1111,'kanoe');

 

이제 가장 간단한 select 쿼리를 날리는 예제를 iBatis로 작성하겠습니다.

 

select pid,pname from tb_Person where pid=2222;

 

이걸 만들겁니다.

사실 php로 코딩하자면 꿀입니다. 아주 간단합니다.

또는 기존의 java로 코딩해도 별거 아닙니다.

 

그냥 아래처럼 코딩하면 됩니다. 이것이 model1 방식입니다.

 

db 이름을 testDB이며 로그인 아이디는 loginId, 패스워드는 1111, 로그인포트 3306인 경우.

 

import java.sql.*;

      class Driver {
        public static void main(String argv[]) {
            try {
                Class.forName("org.gjt.mm.mysql.Driver");
                System.out.println("jdbc 드라이버 로딩 성공");
            } catch (ClassNotFoundException e) {
                System.out.println(e.getMessage());
            }
            try {
                String url = "jdbc:mysql://localhost:3306/testDB";
                Connection con = DriverManager.getConnection(url,"loginId","1111");
                System.out.println("mysql 접속 성공");
                Statement stmt = con.createStatement();
                ResultSet rs = stmt.executeQuery("select pid from tb_Person where pid=2222");
                System.out.println("Got result:");
                while(rs.next()) {
                    String no= rs.getString(1);
                    System.out.println(" no = " + no);
                }
                stmt.close();
                con.close();
            } catch(java.lang.Exception ex) {
                ex.printStackTrace();
            }
        }
      }

 

이러면 끝입니다. 간단합니다.(우선 pid빼기일때..)

머리아프게 iBatis 쓸필요 없습니다.

하지만, 이렇게 살수는 없지 않겠습니까?^^;

파일수도 늘어나고, xml도 써야하고;; 머리아프겠지만, 조금더 함께 고생해봅시다~

쿼리문을 다 xml하나에 모아보자는데....

 

그래서 아래와 같은 총 6개의 파일들이 필요합니다.

이제 하나하나 살펴 보겠습니다.

 

3개의 java 파일과,

apache-tomcat/webapps/myapp/WEB-INF/classes 안에 넣을 다음 3개의 설정파일이 필요합니다..

 

3개의 자바 파일은 myapp 안에 그냥 두면 됩니다.

 

1. MyAppSqlMapConfig.java (ibatis와의 connectionPool 생성 및 db문xml 파싱)

2. Person.java  (id 값을 가져오기 위한 person 클래스입니다.)

3. DBTest.java  ( 이안에 main이 있습니다.)

 

3개의 설정 파일은 apache-tomcat/webapps/myapp/WEB-INF/classes 에 둡니다.


1. Person.xml  (table을 가지고 놀 db 쿼리문을 여기에 xml로 작성하셔야합니다.)

2. SqlMapConfig.properties  (db 연결용 connect 파일, id, pass가 들어있음)

3. SqlMapConfig.xml (ibatis의 핵심 설정 파일. Person.xml등 정의)

설정 파일의 소스를 먼저 본후, 소스를 하나하나 보겠습니다.

 

1. Person.xml

 

<?xml version="1.0"?>
<!DOCTYPE sqlMap PUBLIC "-//iBATIS.com//DTD SQL Map 2.0//EN" "http://www.ibatis.com/dtd/sql-map-2.dtd">
<sqlMap namespace="Person">
<select id="getPerson" resultClass="Person">
    SELECT pid as id,pname as name

    FROM tb_Person
    WHERE
    pid = #value#
</select>
</sqlMap>

 

쿼리문을 하나 만들때 마다 <select id..>를 선언합니다.

getPerson이라고 이름지었는데, 실제 DBTest.java 소스에서 이 getPerson 이름을 사용해서,

이곳을 호출합니다.

pid as id에서 이 id를 알리어스라고 하는데, 이렇게 as id로 알리아스를 해주어야,

자바 프로그램에서 사용이 가능합니다.

이 id라는 것은 Person.java 라는 프로그램에서 실제로 선언한 프로그램 변수명이어야 합니다.

 

2. SqlMapConfig.properties 

 

driver=org.gjt.mm.mysql.Driver
url=jdbc:mysql://localhost:3306/testDB
username=loginId
password=1111

 

이건 그냥 connect 설정입니다.

 

3. SqlMapConfig.xml

 

<?xml version="1.0" ?>
<!DOCTYPE sqlMapConfig PUBLIC "-//iBATIS.com//DTD SQL Map Config 2.0//EN" "http://www.ibatis.com/dtd/sql-map-config-2.dtd">
<sqlMapConfig>
<!--<properties resource="examples/domain/SqlMapConfig.properties" />-->
<properties resource="WEB-INF/classes/SqlMapConfig.properties" />
<!--<properties resource="SqlMapConfig.properties" />-->
<!--These settings control SqlMap configuration details, primarily to do with transaction management. They are all optional (see the Developer Guide for more). -->
<settings
    cacheModelsEnabled="true"
    enhancementEnabled="true"
    lazyLoadingEnabled="true"
    maxRequests="32"
    maxSessions="10"
    maxTransactions="5"
    useStatementNamespaces="false"
/>
<!--Type aliases allow you to use a shorter name for long fully qualified class names. -->
<!--<typeAlias alias="order" type="testdomain.Order" />-->
<!--Configure a datasource to use with this SQL Map using SimpleDataSource.
Notice the use of the properties from the above resource -->
<transactionManager type="JDBC" >
  <dataSource type="SIMPLE">
   <property name="JDBC.Driver" value="${driver}" />
   <property name="JDBC.ConnectionURL" value="${url}" />
   <property name="JDBC.Username" value="${username}" />
   <property name="JDBC.Password" value="${password}" />
  </dataSource>
</transactionManager>
<!--Identify all SQL Map XML files to be loaded by this SQL map. Notice the paths
are relative to the classpath. For now, we only have one… -->
<sqlMap resource="WEB-INF/classes/Person.xml" />
<!--<sqlMap resource="Person.xml" />-->
</sqlMapConfig>

별다른 설명은 필요 없을듯합니다.

제 경우 classpath에 위치 지정을 해줬는데됴, WEB-INF/classes 와 같이 위치 지정을 직접 안하면, 안되더군요.

 

 

이제 자바 소스 들어갑니다.~

 

1. MyAppSqlMapConfig.java (ibatis와의 connectionPool 생성 및 db문xml 파싱)

 

import java.io.*;
import com.ibatis.common.resources.*;
import com.ibatis.sqlmap.client.*;

public class MyAppSqlMapConfig {
        private static final SqlMapClient sqlMap;
        static {
            try {
                    String resource = "SqlMapConfig.xml";
                    Reader reader = Resources.getResourceAsReader(resource);
                    sqlMap = SqlMapClientBuilder.buildSqlMapClient(reader);
            } catch (Exception e) {
                    e.printStackTrace();
                    throw new RuntimeException("Error initializing class. Cause:" + e);
            }
        }

        public static SqlMapClient getSqlMapInstance() {
            return sqlMap;
        }

}

 

2. Person.java  (id 값을 가져오기 위한 person 클래스입니다.)

 

import java.util.*;

public class Person {

    private int id;

    private String name;

    // setter
    public void setId (int id) { this.id = id; }

    // getter
    public int getId () { return id; }

    public void setName (String name) { this.name = name; }

    public String getName () { return name; }

}

 

3. DBTest.java  ( 이안에 main이 있습니다.)

 

import java.sql.SQLException;
import java.util.*;

import com.ibatis.sqlmap.client.*;

public class DBTest {

    /**
     * @param args
     * @throws SQLException
     */
    public static void main(String argv[]) throws SQLException {
        // TODO Auto-generated method stub
        // select
        /*
        */
        selectTest();
    }

    public static void selectTest () throws SQLException
    {
        //sqlMap 초기화(MyAppSqlConfig.java)
        SqlMapClient sqlMap = MyAppSqlMapConfig.getSqlMapInstance();


        Integer personId = 2222;
        //Person.xml 안의 ID가 getPerson인 DB 선언에서 값이 psersonId(2222)인것을 select>해옴
        Person person = (Person) sqlMap.queryForObject("getPerson",personId);

        System.out.println("- Id : " + person.getId());

        System.out.println("- name : " + person.getName());

        System.out.println("\\nSelect Done");
    }

}

 

짝짝짝...

그대로 한번 꼭 해보시길 바랍니다.

 

결과는

 

- Id: 2222

- name: wono

 

라고 나오겠지요? ^^

 

저도 처음에 남이 하는걸 볼때는 쉬워 보였는데, 직접 해볼려니 어렵더군요.

 

아, 컴파일은 각각 해주시면 됩니다.(아직 모든 파일들을 한방에 쏵~ 컴파일 해주는 ant 설정은 해주지 않았습니다. 뒷 강좌에서 리눅스 ant에 대해 다루겠습니다.^^)

 

1. javac MyAppSqlMapConfig.java

2. javac Person.java 

3. javac DBTest.java 

 

그리고, java DBTest 라고 해주시면...

값을 확인해 보실수 있습니다.^^

 

 

이 강좌를 iBatis를 처음 접하는 저와 같은 모든 이땅의 java, jsp 초보프로그래머에게 바칩니다.

조금이라도 도움이 되셨다면, 덧글이라도 살짝 남겨주세요. 감사합니다.

 

iBatis 사이트(http://ibatis.apache.org/javadownloads.html)의 이동국님께서 올려주신 메뉴얼을 많이 참고하였음을 밝히며, 조금밖에 안바꼈지만, 본 강좌의 저작권은 wono77에게 있습니다.

퍼가실때는 스크랩을 해주세요. 감사합니다. ^^ (__)

 

이제 이 iBatis의 기능으로 insert, delete, update 를 추가해서 게시판을 만들거나, struts, spring, log4j 같은 프레임웍을 조금씩 얹어가볼 생각입니다.

강좌는 계속 수정,보완되며... 진행 될 예정입니다.^^

'DB' 카테고리의 다른 글

ibatis에서 map 사용하기.  (0) 2007.10.03
delete, truncate, drop의 차이점  (0) 2007.09.27
ORA-01013 에러  (0) 2007.09.23
mysql 쿼리 모니터링 mytop  (0) 2007.09.12
mysql 모니터링하기  (0) 2007.09.12
Posted by '김용환'
,

ORA-01013 에러

DB 2007. 9. 23. 03:58

ORA-01013user requested cancel of current operation

Cause:The user interrupted an ORACLE operation by entering CTRL-C (ControlC) or another canceling operation. This forces the current operation to end. This is an informational message only.

Action:Continue with the next operation.

 

 

 

sqlnet.ora  파일의 sqlnet.expire_time를 체크해 볼 것.

Posted by '김용환'
,

mysql 쿼리 모니터링 mytop

DB 2007. 9. 12. 07:08

모니터링 툴이다.

mytop - a top clone for MySQL

 

 

설치

 

1. DBI Install

# tar xvzf DBI.tar.gz
# cd DBI
# perl Makefile.PL
# make
# make install


 

2. DBD-Mysql Install

# tar xvzf DBD-Mysql.tar.gz
# cd DBD-Mysql
# perl Makefile.PL
# make
# make install

 

3. Term::ReadKey Install

# tar xvzf TermReadKey.tar.gz
# cd TermReadKey
# perl Makefile.PL
# make
# make install

 

 

4. mytop Install

# tar xvzf mytop.tar.gz
# cd mytop
# perl Makefile.PL
# make
# make install
-------------------------------------

 

홈디렉터리에 다음 파일을 만든다.

 

# vi .mytop
user=root
pass=password
host=localhost
db=cast

 

 

또는

  user=root
  pass=
  host=localhost
  db=test
  delay=5
  port=3306
  socket=
  batchmode=0
  header=1
  color=1
  idle=1

 

이렇게 사용가능하다.

 

 

http://jeremy.zawodny.com/mysql/mytop/mytop.html

설명을 보니, ansi color를 이용해서 색깔도 낼 수 있다.

 

<옵션 설명>
d - 특정 디비에 대해서만 보는 경우
f - 지정된 쓰레드가 실행중인 쿼리를 모두 출력
h - 간단히 보기
i - 쉬고있는 쓰레드는 리스트에서 제외
k - 쓰레드 연결을 종료
m - 초당 실행 쿼리수 보기
p - 화면 정지
q - mytop 종료
r - FLUSH STATUS 실행
s - 화면 갱신 시간 설정
u - 특정 사용자의 쓰레드만 보기

 

 

출처 :

mytop : http://jeremy.zawodny.com/mysql/mytop/

펄 모듈 : http://search.cpan.org/

 

Posted by '김용환'
,