8일차 수업 ( 문자열 , 예외처리 )

1. 문자열 생성방법
. String 클래스 이용
- 한번 생성된 문자열은 변경안된다.
- 메소드를 사용하여 가공하면 새로운 문자열이 생성된다

따라서 문자열 조작이 적은 경우에 사용한다.

 

- 리터럴 이용
  > String str = "hello";
      String str3 = "hello";
   => literal pool 메모리에 생성된다.
      기존 문자열이 존자하면 재사용 한다.     
- new 이용
  > String str2 = new String("hello");
      String str4 = new String("hello");
   => heap 메모리에 생성된다. 매번 생성된다.
   - 메소드 정리

. StringBuffer 클래스 이용
- 한번생성된 문자열이 변경된다. 따라서 문자열 조작이 많은 경우에 사용된다.


   - new 이용
   > StringBuffer buffer = new StringBuffer("hello");

. toString 메소드 이용
=> 정수를 문자열로 변경
   String str = Integer.toStirng(123);
   String str2 = Float.toStirng(123.4F);

. + (연결 연산자) 이용
=> 문자열과 다른 데이터형이 + 만나면 자동으로 문자열로 변경된다.
 > System.out.println( 1 + 2 ); // 3
     System.out.println(1+ " " + 2); 1 2

     int x = 123;
     String str = x+""; // 권장 안함.
     String str2 = Integer.toStirng(123);
     String str3 = String.valueof(123);

 

<문자열의 다양한 처리방법>

 

  String str = "SJgood";
  
  //1. 모든 문자열을 대문자로 만들기
  System.out.println(str.toUpperCase());  //SJGOOD
  //2. 모든 문자열을 소문자로 만들기
  System.out.println(str.toLowerCase()); //sjgood
  //3. 문자열 부분 출력
  System.out.println(str.substring(0,2));  //SJ
  System.out.println(str.substring(2,6)); //good

 

2. 예외처리
예외( exception )?
=> 일반적으로 '에러'라고 부른다.
 ( '예외가 발생' 한다고 부른다. )
=> 예외가 발생되면 '프로그램이 비정상' 종료된다. (****)

>
 문장1;
 문장2;
 문장3;
 ...

 문장100;
 system.out.println("프로그램 정상종료");
 }.//end main

순차문이기 때문에 한번 실행된 문장을 다시 실행할 수 없다.
(반복문 제외)

 

<예외 처리 하는 방법>

Try ~ catch문 사용하기!
문법 :

 try{
     //예외발생코드
 }catch{예외클래스 변수명){
  //예외처리 코드
 }
* 다중 catch
- try 블럭안에 여러개의 문장이 지정 가능하다.
이 문장들이 서로 다른 예외가 발생가능하기 때문에 catch문도 여러개가 필요하다.

 try{
  문장1; => ArithmeticException
  문장2; => NullPointerException
  문장3; => ClassCastException
 }catch(ArithmeticException e){

 }catch(NullPointerException e){

 }catch(ClassCastException e){

 }

* finally
=> 예외가 발생유무와 상관없이 항상 실행되는 문장.
=> System.exit(0) 제외하고는 어떤 상황에서도 반드시 수행된다.
=> 주요용도: 파일 또는 데이터베이스와 같은 외부자원을 사용하고 close 하는 작업에 사용된다.


 try{

 }catch(){

 }finally{
 //반드시 수행되는 문장
 } 

 

====수업 내용======

 

1. 문자열 생성방법
가. String 클래스 이용
- 한번 생성된 문자열은 변경안되.ㅁ
  메소드를 사용하여 가공하면 새로운 문자열이 생성된다.
  따라서 문자열 조작이 적은 경우에 사용한다.
- 리터럴 이용
  예> String str = "hello";
      String str3 = "hello";
   => literal pool 메모리에 생성된다.
      기존 문자열이 존자하면 재사용 한다.     
- new 이용
  예> String str2 = new String("hello");
      String str4 = new String("hello");
   => heap 메모리에 생성된다. 매번 생성된다.
   - 메소드 정리
 
나. StringBuffer 클래스 이용
- 한번생성된 문자열이 변경된다. 따라서 문자열 조작이 많은 경우에 사용된다.
-
   - new 이용
   예> StringBuffer buffer = new StringBuffer("hello");
다. toString 메소드 이용
=> 정수를 문자열로 변경
   String str = Integer.toStirng(123);
   String str2 = Float.toStirng(123.4F);
라. + (연결 연산자) 이용
=> 문자열과 다른 데이터형이 + 만나면 자동으로 문자열로 변경된다.
 예> System.out.println( 1 + 2 ); // 3
     System.out.println(1+ " " + 2); 1 2
     int x = 123;
     String str = x+""; // 권장 안함.
     String str2 = Integer.toStirng(123);
     String str3 = String.valueof(123);
2. wrapper 클래스 : 기본형 데이터에 해당되는 클래스들의 묶음
기본형                         클래스
--------------------------------------
byte                            Byte
short    Short
int    Integer
long    Long
char    Character
float    Float
double    Double
boolean    Boolean
제공된 이유 : 기본형과 관련된 작업을 효율적으로 하기 위해서 제공됨
예> 숫자 --> 문자
    문자 --> 숫자
    int 범위 ?
    문자 대문자? 소문자?
3. 자동형변환
: 기본형  -------> Wrapper ( auto boxing )
  Wrapper -------> 기본형  ( auto unboxing )

4. Random 클래스
* 랜덤값 얻는 2가지 방법
가. Math.random();
0.0 <= <1.0
나. Random 클래스
: nextInt(n) ==> 0 ~ n-1 의 임의의 정수값 리턴
5. StringTokenizer 클래스
용도 : 특정구분문자로 분리된 통문자열에서 구분자를 기준으로 원하는 문자열을 얻는 방법
예> "홍길동 20 서울 " "
6. 날짜 데이터
Date
Calendar
7. 예외처리
- 예외( exception )?
=> 일반적으로 '에러'라고 부른다.
 ( '예외가 발생' 한다고 부른다. )
=> 예외가 발생되면 '프로그램이 비정상' 종료된다. (****)
예>
 문장1;
 문장2;
 문장3;
 ...
 문장100;
 system.out.println("프로그램 정상종료");
 }.//end main
순차문이기 때문에 한번 실행된 문장을 다시 실행할 수 없다.
(반복문 제외)
-예외처리를 담당하는 클래스가 제공된다. ( 예외 클래스 )
  Object
  Throwable
  Exception (
RuntimeException  IOException
NullPointerException  FileNotFoundException,
ArithmeticException
ArrayIndexOutbounds
ClassCastException
- 예외처리 방법 2가지
가. Try ~ catch문
문법 :
 try{
     //예외발생코드
 }catch{예외클래스 변수명){
  //예외처리 코드
 }
* 다중 catch문
- try 블럭안에 여러개의 문장이 지정 가능하다.
이 문장들이 서로 다른 예외가 발생가능하기 때문에 catch문도 여러개가 필요하다.
 try{
  문장1; => ArithmeticException
  문장2; => NullPointerException
  문장3; => ClassCastException
 }catch(ArithmeticException e){
 }catch(NullPointerException e){
 }catch(ClassCastException e){
 }
* finally 문
=> 예외가 발생유무와 상관없이 항상 실행되는 문장.
=> System.exit(0) 제외하고는 어떤 상황에서도 반드시 수행된다.
=> 주요용도: 파일 또는 데이터베이스와 같은 외부자원을 사용하고 close 하는 작업에 사용된다.

 try{
 }catch(){
 }finally{
 //반드시 수행되는 문장
 }
나. throws 키워드 이용
 
블로그 이미지

itworldkorea

IT korea가 세상(world)을 변화시킨다.

,

MySQL 테이블이 존재 여부 확인하는 소스.  DB 관련 함수

 

<?
$link = mysql_connect("localhost", "root", "apmsetup");


$a = mysql_list_tables("hello");

$num = mysql_num_rows($a);

echo $num ;

for ($i = 0; $i < $num; $i++){
 $s = mysql_tablename($a,$i);
 if($s == "user_tbl"){
  echo "exists";
  exit;
 }
 
 
 
}
echo "end";
?>

블로그 이미지

itworldkorea

IT korea가 세상(world)을 변화시킨다.

,

MySQL 테이블 이름 불러오는 함수 mysql_tablename ()  DB 관련 함수

 

테이블 이름을 불러오는 함수로 mysql_table(인자1,인자2)가 있다.

 

인자1에 쿼리문 2에 변수를 넣는다.

 

사용법 :

 

<?php
mysql_connect("localhost", "root", "apmsetup");
$result = mysql_list_tables("hello");
$num_rows = mysql_num_rows($result);
for ($i = 0; $i < $num_rows; $i++) {
    echo "Table: ", mysql_tablename($result, $i), "\n";
}

mysql_free_result($result);
?>

블로그 이미지

itworldkorea

IT korea가 세상(world)을 변화시킨다.

,

MySQL 현재 서버의 상태를 보는 함수 mysql_stat()  DB 관련 함수

 

현재 서버의 상태를 알려주는 함수로 mysql_stat() 가 있다.

 

사용법 :

 

<?
$link = mysql_connect("localhost", "root", "apmsetup");
mysql_select_db("hello");

$a = mysql_stat($link);

echo $a ;


 ?>

 

 

결과

 

Uptime: 18203 Threads: 2 Questions: 590 Slow queries: 0 Opens: 21 Flush tables: 1 Open tables: 0 Queries per second avg: 0.32

블로그 이미지

itworldkorea

IT korea가 세상(world)을 변화시킨다.

,

MySQL 테이블 리스트 보기 show tables from dbname  DB 관련 함수


다음은 특정 DB의 테이블 목록을 보는 소스이다.

 

<?
$link = mysql_connect("localhost", "root", "apmsetup");
mysql_select_db("hello");

$db_name = "hello"; // hello 대신 db이름을 적는다.

$sql = "show tables from $db_name";
$result = mysql_query($sql);

while ($row = mysql_fetch_row($result)){
echo "$row[0] <br />";
}

mysql_free_result($result);

 ?>

블로그 이미지

itworldkorea

IT korea가 세상(world)을 변화시킨다.

,

MySQL 데이터베이스 목록 불러오기 mysql_list_dbs()  DB 관련 함수

 

데이터 베이스 목록을 불러 오기 위한 함수 mysql_list_dbs()를 사용하면 된다.

 

사용법 :

 

 <?
$link = mysql_connect("localhost", "root", "apmsetup");
mysql_select_db("hello");

$db_list = mysql_list_dbs($link);

echo "$db_list";

while ($row = mysql_fetch_object($db_list)){
echo "$row->Database <br />";
}


 ?>

블로그 이미지

itworldkorea

IT korea가 세상(world)을 변화시킨다.

,

MySQL 필드의 이름을 불러오는 함수 mysql_field_name  DB 관련 함수

 

필드의 이름을 불러오는 함수는

 

mysql_field_name()

 

이다.

 

mysql_field_name (쿼리변수,필드순서);

 

 

사용법 :

 

<?
mysql_connect("localhost", "root", "apmsetup");
mysql_select_db("hello");

$result = mysql_query("SELECT * FROM user_tbl WHERE userid = 'david'");


$res = mysql_query('select * from user_tbl');

echo mysql_field_name($res, 0)
 ?>

블로그 이미지

itworldkorea

IT korea가 세상(world)을 변화시킨다.

,

MySQL 필드의 바이트 값을 구하는 함수 mysql_field_len()  DB 관련 함수


필드의 바이트 값을 구하는 함수는 mysql_field_len()이다.

 

사용법은

 

 <?
mysql_connect("localhost", "root", "apmsetup");
mysql_select_db("hello");

$result = mysql_query("SELECT * FROM user_tbl WHERE userid = 'david'");


$length = mysql_field_len($result, 5);
echo $length;


 ?>

 

결과 

 

11

---------------------------------------------

 

 

 

 

블로그 이미지

itworldkorea

IT korea가 세상(world)을 변화시킨다.

,

MySQL 행과 일치하는 값의 레코드 불러오기 mysql_fetch_row()  DB 관련 함수


<?
mysql_connect("localhost", "root", "apmsetup");
mysql_select_db("hello");

$result = mysql_query("select *from user_tbl where userid = 'david'");
if(!$result){
 echo mysql_error();
 exit;
}
$row = mysql_fetch_row($result);

$sql = mysql_query("select *from user_tbl");
$num_fields = mysql_num_fields($sql);

 

for($a = 0; $a < $num_fields;$a++){
 echo "$a :  $row[$a] <br />";
}
 ?>

블로그 이미지

itworldkorea

IT korea가 세상(world)을 변화시킨다.

,

MySQL 테이블의 필드의 갯수를 구하는 함수 mysql_num_fields()  DB 관련 함수

 

MySQL 에서 테이블의 필드를 수를 구하는 함수는 mysql_num_fiedls() 이다.

 

그럼 소스를 통해서 살펴보자.

 

<?php
$conn = mysql_connect("localhost","root","apmsetup") or die ("My SQL connection Error");

mysql_select_db('hello');


$result = mysql_query('select *from user_tbl') or die("no table");

$a = mysql_num_fields($result);  //
 
echo "필드의 갯수 : $a ";


?>

블로그 이미지

itworldkorea

IT korea가 세상(world)을 변화시킨다.

,