카테고리 보관물: java

Mysql Insert 오류

Mysql Insert를  1 행씩 하다 보니 성능이 너무 저질이라… insert into table values (),(),()…()
의 문법을 사용해서 하려고 했는데.. 데이터를 좀 많이 넣으니.. 아래와 같은 오류가 출력되었습니다.


 

com.mysql.jdbc.PacketTooBigException: Packet for query is too large (1146237 > 1048576). You can change this value on the server by setting the max_allowed_packet' variable.

    at com.mysql.jdbc.MysqlIO.send(MysqlIO.java:2584)

    at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:1554)

    at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:1665)

    at com.mysql.jdbc.Connection.execSQL(Connection.java:3170)

    at com.mysql.jdbc.Statement.executeUpdate(Statement.java:1316)

    at com.mysql.jdbc.Statement.executeUpdate(Statement.java:1235)

    at org.apache.commons.dbcp.DelegatingStatement.executeUpdate(DelegatingStatement.java:225)

    at org.springframework.jdbc.core.JdbcTemplate$1UpdateStatementCallback.doInStatement(JdbcTemplate.java:457)

    at org.springframework.jdbc.core.JdbcTemplate.execute(JdbcTemplate.java:341)

    at org.springframework.jdbc.core.JdbcTemplate.update(JdbcTemplate.java:467)

 

한번에 실행할 수 있는 패킷의 양이 정해져 있습니다. 덤으로 콘솔 로그를 무한으로 찍해 놓은 저의 PC도 먹통이 된것 처럼 느려지게 되었습니다. 이클립스 콘솔로그 사이즈를 정해야 겠습니다.

쿼리를 통해 조회해 보니

mysql> show variables like ‘max%’;
+—————————-+———————-+
| Variable_name              | Value                |
+—————————-+———————-+
| max_allowed_packet         | 1048576              |
| max_binlog_cache_size      | 4294963200           |
| max_binlog_size            | 1073741824           |
| max_connect_errors         | 10                   |
| max_connections            | 100                  |
| max_delayed_threads        | 20                   |
| max_error_count            | 64                   |
| max_heap_table_size        | 16777216             |
| max_insert_delayed_threads | 20                   |
| max_join_size              | 18446744073709551615 |
| max_length_for_sort_data   | 1024                 |
| max_prepared_stmt_count    | 16382                |
| max_relay_log_size         | 0                    |
| max_seeks_for_key          | 4294967295           |
| max_sort_length            | 1024                 |
| max_sp_recursion_depth     | 0                    |
| max_tmp_tables             | 32                   |
| max_user_connections       | 0                    |
| max_write_lock_count       | 4294967295           |
+—————————-+———————-+
19 rows in set (0.00 sec)

mysql>

mysql>
mysql>
set global max_allowed_packet= 1024*1024*32;
Query OK, 0 rows affected (0.02 sec)

 

32M 로 설정 완료.. 다시 실행 해봅시다.

이 글은 java 카테고리에 분류되었고 태그가 있으며 님에 의해 에 작성되었습니다.

Swap without temp value

강의를 듣는 중에 강사님이 Temp 값 없이 Swap 하는 방법을 말씀하셔서 검색하니…
물론 C에서 하는 방법은 다르지만 .. 흥미롭게 할 수 있는 방법이 있어.. 포스팅을 합니다.

int a = 100;


int b = 120;


System.out.println("before:  a=" +a + " b=" + b);


b = (a+b);


a = (b-a);


b = (b-a);


System.out.println("after:   a=" +a + " b=" + b);

HashTable 값 출력

import java.util.Collection;

import java.util.Enumeration;

import java.util.Hashtable;

import java.util.Iterator;

import java.util.Set;

 

public class TestClient {

    public static void main(String[] args)  {

        /*

         * HashTable 간략 정리

         * 1. Key와 Value에 NULL 을 허용하지 않음

         * 2. 동기화 (Synchronized)

         * 3. 중복 허용 안함.

         */

 

        // Hashtable 생성

        Hashtable hashTable =

                new  Hashtable();

 

        hashTable.put("연예인", "김태희");

        hashTable.put("연예인", "송승헌");

        hashTable.put("연예인", "이병헌");

        hashTable.put("연예인", "조인성");

        // 중복이 없습니다.

        System.out.println(hashTable.size());

 

        // 값을 출력합니다.

        Collection values = hashTable.values();

        for (String string : values) {

            // 결과는 조인성 입니다.

            // 마지막에 입력된 값이 조인성 이기 때문에.

            System.out.println(string);

        }

 

        hashTable.put("연예인", "김태희");

        hashTable.put("아이돌", "아이유");

        hashTable.put("영화배우", "이병헌");

        hashTable.put("가수", "김경호");

        /*

         * HashTable 데이터를 출력하는 방법

         * 1. Key값으로 객체를 찾음

         * 2. values 를 사용하여 Collection 형태로 찾음

         */

 

        // 방법 1

        Enumeration keys = hashTable.keys();

        while (keys.hasMoreElements()) {

            // Key 를 찾고 찾은 key로 Value를 찾습니다.

            String key = (String) keys.nextElement();

            System.out.println("Key: "+ key +" value: "+ hashTable.get(key));

        }

 

        // 방법 2

        Collection tableValues = hashTable.values();

        for (String value : tableValues) {

            System.out.println("value: "+ value);

        }

 

        // 방법 3

        Set keySet = hashTable.keySet();

        Iterator iterKey = keySet.iterator();

        while(iterKey.hasNext()) {

            String key = iterKey.next();

            System.out.println("Key: "+ key +" value: "+ hashTable.get(key));

        }

 

        /*

         * 물론 어떻게 사용하느냐에 따라 다르겠지만

         * 1, 3번 방법은

         * Key값에 해당하는 Value를 찾을 때 주로 사용 하고

         *

         * 2.번 방법은

         * value를 나열 할때 주로 사용합니다.

         * 특정 키와 상관 없이 모든 value를 사용할 때 사용합니다.

         *

         */

    }

}

랜카드 정보 조회

라이선스 적용을 위해 랜카드 정보를 찾는데 기존 방식은
Runtime.getRuntime().exec(“ipconfig /all”);
을 사용하여 InputStream 으로 추출 했습니다.  이렇게 하는 방법 외에 다른 방법을 해보니 예전에 특정아이피로 바인딩 하는 방법에서 찾을 수 있을 것 같아. 아래와 같이 해봤습니다.

간단하게 맥어드레스와 이름 만 출력 합니다.

// 설치된 모든 랜카드 정보를 얻는다.
 Enumeration netEnumeration =  NetworkInterface.getNetworkInterfaces();

 while (netEnumeration.hasMoreElements()) {

    // 랜카드 목록에서 랜카드 하나의 정보를 추출한다.
    NetworkInterface networkInterface = (NetworkInterface) netEnumeration.nextElement();

    // 맥어드레스를 추출
    byte[] data = networkInterface.getHardwareAddress();
    if(data == null || data.length != 6) {
        continue;
    }


    StringBuilder macAddress = new StringBuilder();

    // 맥어드레스를 읽기 쉬운 타입 => 00:00:00:00:00:00 형식으로 변환한다.
    for (int i = 0; i < data.length; i++) {
        macAddress.append(Integer.toHexString(0x10000 | (0xff & (int)data[ 0 + i])).substring(3, 5).toUpperCase())
        if (i != 5)
            macAddress.append(":");
    }


    // 출력한다.
    System.out.println("NAME:" + networkInterface.getDisplayName());
    System.out.println("MAC: " + macAddress.toString());
 }

HttpClient 4.0 Post 방식 한글깨짐

Post Method 로 한글 데이터를 전송하니 깨져서…
구글신의 도움을 받아.

HttpPost httpost = new HttpPost("http://coozplz.blogspot.com"); 
List nvps = new ArrayList();
nvps.add(new BasicNameValuePair("MESSAGE", "안녕하세요"));
httpost.setEntity(new UrlEncodedFormEntity(nvps, "euc-kr"));
httpost.setHeader("Content-type", "application/x-www-form-urlencoded");
HttpClient httpClient = new DefaultHttpClient();
HttpResponse response = httpClient.execute(httpost);

Java Split()

 

Question:


split 사용법에 대해서 모르는게 많은데요. split 즉 문자를 쪽는 것인데, string[] wordsplit=str.split(‘ ‘); 이 하 코드에서 이렇게 하면은 12,33,23,15,17이렇게 나오고 ‘,’,’,’,’이렇게 하면은 17이렇게 나오는데, 자기가 원하는 값을 구할려면은 split 함수를 잘 알아야 겠는데, split 함수 사용법을 알려주세요.

string str= "12,33,23,15,17";

string[] wordsplit= str.split(' ');

for(int i=0; i&lt;wordsplit.Length; i++) {

	textResult.Text=wordsplit[i];

}

 

Answer: 

public class SplitTest {
    public static void main(String[] args) {
	String str = "12,33,23,15,17";
	// ','를 기준으로 Split()
	String[] strArr = str.split(","); 
	for (String string : strArr) {
		System.out.print(string+"\t");
	}
	System.out.println();
	str = "12 33 23 15 17";
	// ' '을 기준으로 Split()
	strArr = str.split(" ");
	for (String string : strArr) {
		System.out.print(string+"\t");
	}
	System.out.println();
	str = "12|33|23|15|17";
	// '|' 를 기준으로 Split() 
	strArr = str.split("|");
	for (String string : strArr) {
		System.out.print(string+"\t");
	}
	System.out.println();
	str = "12|33|23|15|17";
	strArr = str.split("\\|");
	for (String string : strArr) {
		System.out.print(string+"\t");
	}
	System.out.println();
	str = "12*33*23*15*17";
	strArr = str.split("\\*");
	for (String string : strArr) {
		System.out.print(string+"\t");
	}
    }
}
먼저 split 함수를 API 에서 찾아 보면 아래와 같이 나옵니다.