SQLite

http://www.sqlite.org/ 접속. Download 탭에가서, 윈도우즈 용인 Precompiled Binaries for Windows 에서 sqlite-shell-win32-x86-3080403.zip(289.42 KiB)  다운.

압축풀고, C:에 SqliteRoom을 만들고 압축푼, sqlite3.exe를 넣음.

커맨드창에가서 SqliteRoom으로 이동해서 sqlite3 하면 sqlite가 실행됨.   .quit하면 종료.

sqlite3 test.db 입력하면 아직 test.db가 만들어진게 아니라, 테이블을 하나만들면 test.db가 만들어짐.

어제와 같은 것을 만들어보면

CREATE TABLE helloworld 엔터

(

id integer primary key,

pwd varchar(20) NOT NULL

);

을 입력한다.

.schema helloworld 를 입력하면 방금 입력한 소스를 다보여준다.

INSERT INTO helloworld VALUES(1, '1234');

INSERT INTO helloworld(pwd) VALUES('3333');

INSERT INTO helloworld(pwd) VALUES('P@$$WOrd'); 

//아이디는 자동으로 1씩 증가하기 때문에 주지않아도된다.

.show를 치면 현재 sqlite의 세팅된 환경설정을 보여준다.

.mode column 을 쳐서 모드를 바꾸고

.headers on  을 쳐서 세팅바꾸면.

그리고 select * from helloworld; 를 치면 보기 편하게 바뀐것을 볼 수 있다.

.quit로 빠져나온다.

구글에서 sqlite database browser 를 쳐서 가장 위에 사이트에 들어가서 녹색 다운로드 버튼 클릭.

다운받은 것을 알집을 풀고 폴더의 이름을 Sqlite Database Browser 로 이름을 바꾼다. 폴더를 C:\ProgramFiles 에 넣는다.

그리고 SQLite Database Browser 를 실행시키고 아까 만든 test.db를 오픈하면 내용을 볼 수 있음. 장점은 커맨드명령을 싫어한는 사람을 위한.


이클립스 sql explorer - new profile 에가서 설정.

구글에서 sqlite jdbc driver 검색. 제일 위 사이트 클릭. downloads 탭 선택. sqlite-jdbc4-3.8.2-SNAPSHOT.jar 다운.

받은 jar파일을 C:\SqliteRoom 에 넣어줌. 그리고 add/edit 들어가서 sqlite-edit 눌러서 방금 jar파일을 add jars해서 추가해주고 리스트드라이버 잡아주고 

URL을 jdbc:sqlite:C:/sqliteroom/test.db로 바꿔줌. ok해서 Name을 Sqlite3해주고 User~~~체크, Auto Commit 체크 ~~ ok.

연결시켜주고 select * from helloworld; 하면 안되네.-> 오른쪽에 Tables에 helloworld 눌러서 다시 해주면 된다.


다시 sql editor 창에서 

CREATE TABLE telephone

(

  telnum CHAR(8) PRIMARY KEY,

  gubun INTEGER NOT NULL,

  irum VARCHAR(20) NOT NULL,

  howmany INTEGER NOT NULL,

  gibon INTEGER,

  fee INTEGER,

  tax INTEGER,

  total INTEGER

);

run 하고 오른쪽에 Tables를 refresh하면 telephone table이 들어온 것을 볼 수 있다.


이클립스의 전화요금 관리프로그램의 우측버튼 built path-configuration build path 들어가서libraries 탭에서 add External JARs에서 sqliteroom의 jar파일을 선택해준다.

main에서 

import java.sql.Connection;

import java.sql.DriverManager;

import java.sql.SQLException;

import java.sql.Statement;

import java.util.Scanner;


public class Main {

public static void main(String[] args) {

//2. Driver Loading

try {

Class.forName("org.sqlite.JDBC");

System.out.println("Loading Success");

} catch (ClassNotFoundException e) {

System.out.println("Class Not Found");

}

//3. Connection

Connection conn = null;

String str = "jdbc:sqlite:C:/sqliteroom/test.db";

try{

conn = DriverManager.getConnection(str);

System.out.println("Connection Success");

}catch(SQLException ex){

System.out.println("Connection failure");

}

}

}

이렇게 해서 실행 시켜주어 connection 까지 완료한다.


dbinf.properties를 프로젝트에 넣어주고 내용을

DBDRIVER=org.sqlite.JDBC

DBURL=jdbc:sqlite:C:/SqliteRoom/test.db

로 바꿔줌.

다시 main을 

import java.sql.SQLException;

import java.sql.Statement;

import java.util.Scanner;


public class Main {

public static void main(String[] args) {

System.out.println("<<전화요금관리프로그램>>");

Scanner scan = new Scanner(System.in);

Main main = new Main();

int choice = 0;

while(true){

choice = main.showMenu(scan);

if(choice == 4) break;

switch(choice){

case 1 : Input input = new Input(scan);  input.input(); break; 

case 2 : Output output = new Output(); break;

case 3 : Search search = new Search(scan); search.search(); break;

}

}

System.out.println("Program is over...");

}

int showMenu(Scanner scan){

System.out.println("1:입력, 2:출력, 3:검색, 4:종료");

System.out.print(">> ");

return scan.nextInt();

}

}

이렇게 바꿔주고, 

DBConnection도

import java.io.FileInputStream;

import java.io.FileNotFoundException;

import java.io.IOException;

import java.sql.Connection;

import java.util.Properties;


public class DBConnection{

private Properties info = null;

private Connection conn = null;

public DBConnection(){

info = new Properties();

try{

info.load(new FileInputStream("dbinfo.properties"));

}catch(FileNotFoundException ex){ ex.printStackTrace(); 

}catch(IOException ex){ ex.printStackTrace(); }

}

public void loadDriver(){

try{

Class.forName(info.getProperty("DBDRIVER"));

}catch(ClassNotFoundException ex){

System.out.println("Class Not Found");

}

}

public void setConnection(){

String url = info.getProperty("DBURL");

try{

conn = java.sql.DriverManager.getConnection(url);

}catch(java.sql.SQLException ex){

System.out.println("Cannot Connect Access");

}

}

public Connection getConnection(){

if(this.conn != null) return this.conn;

else return null;

}

}

이렇게 바꿔줌(바꿔준건 dbinf.properties의 경로밖에없음. 그냥 자바프로젝트에 넣어주어서)

실행하면 잘됨. 몇명 입력하고 Sqlite Database Browser로 확인하면 입력된 것을 볼 수 있다.


전화요금관리프로그램에서 delete만 추가된 버전을 만들면(수정한 것만 적음)

import java.sql.SQLException;

import java.sql.Statement;

import java.util.Scanner;


public class Main {

public static void main(String[] args) {

/* //2. Driver Loading

try {

Class.forName("org.sqlite.JDBC");

System.out.println("Loading Success");

} catch (ClassNotFoundException e) {

System.out.println("Class Not Found");

}

//3. Connection

Connection conn = null;

String str = "jdbc:sqlite:C:/sqliteroom/test.db";

try{

conn = DriverManager.getConnection(str);

System.out.println("Connection Success");

}catch(SQLException ex){

System.out.println("Connection failure");

}

//4. Statement 객체 생성

Statement stmt = null;

try{

stmt = conn.createStatement();

//5. Query 실행

StringBuffer sb = new StringBuffer();

sb.append("CREATE TABLE telephone(");

sb.append("telnum    CHAR(8)  PRIMARY KEY, ");

sb.append("gubun   INTEGER   NOT NULL,");

sb.append("irum    VARCHAR(20)  NOT NULL,");

sb.append("howmany   INTEGER   NOT NULL,");

sb.append("gibon   INTEGER,");

sb.append("fee   INTEGER, ");

sb.append("tax   INTEGER, ");

sb.append("total  INTEGER)");

stmt.executeUpdate(sb.toString());

System.out.println("Table Creation Success");

}catch(SQLException ex){

ex.printStackTrace();

}

try{

if(stmt != null) stmt.close();

if(conn != null) conn.close();

}catch(SQLException ex){

ex.printStackTrace();

}*/

System.out.println("<<전화요금관리프로그램>>");

Scanner scan = new Scanner(System.in);

Main main = new Main();

int choice = 0;

while(true){

choice = main.showMenu(scan);

if(choice == 6) break;

switch(choice){

case 1 : Input input = new Input(scan);  input.input(); break; 

case 2 : Output output = new Output(); break;

case 3 : Search search = new Search(scan); search.search(); break;

case 4 : Delete delete = new Delete(scan); delete.delete(); break; 

//case 5 :

}

}

System.out.println("Program is over...");

}

int showMenu(Scanner scan){

System.out.println("1:입력, 2:출력, 3:검색, 4:삭제, 5:수정, 6:종료");

System.out.print(">> ");

return scan.nextInt();

}

}





import java.util.Scanner;

import java.util.Vector;



public class Delete {


private Scanner scan;

Delete(Scanner scan){

this.scan = scan;

}

void delete(){

System.out.print("1.이름으로 삭제,  2. 전화번호로 삭제 : ");

int choice = this.scan.nextInt();

this.scan.nextLine();

String sql = null;

if(choice == 1){  //이름으로 삭제

System.out.print("이름 : ");

String name = scan.nextLine();

sql = "DELETE FROM telephone WHERE irum = '" + name + "'";

}else if(choice == 2){   //전화번호로 삭제

System.out.print("전화번호 : ");

String telnum = scan.nextLine();

sql = "DELETE FROM telephone WHERE telnum = '" + telnum + "'";

}

CustomerController.delete(sql);

}

}






import java.sql.Connection;

import java.util.Vector;



public class CustomerController {

public static void delete(String sql){

DBConnection db = new DBConnection();

db.loadDriver();

db.setConnection();

Connection conn = db.getConnection();

CustomerDAO.delete(conn, sql);

DBClose.close(conn);

}

public static Vector<CustomerVO> search(String sql){

DBConnection db = new DBConnection();

db.loadDriver();

db.setConnection();

Connection conn = db.getConnection();

Vector<CustomerVO> vector = CustomerDAO.search(conn, sql);

DBClose.close(conn);

return vector;

}

public static void insert(CustomerVO c){

DBConnection db = new DBConnection();

db.loadDriver();

db.setConnection();

Connection conn = db.getConnection();

CustomerDAO.insert(conn, c);

DBClose.close(conn);

}

public static Vector<CustomerVO> select(){

DBConnection db = new DBConnection();

db.loadDriver();

db.setConnection();

Connection conn = db.getConnection();

Vector<CustomerVO> vector = CustomerDAO.select(conn);

DBClose.close(conn);

return vector;

}

}








import java.sql.Connection;

import java.sql.ResultSet;

import java.sql.SQLException;

import java.sql.Statement;

import java.util.Vector;


public class CustomerDAO {

public static void delete(Connection conn, String sql){

Statement stmt = null;

try {

stmt = conn.createStatement();

stmt.executeUpdate(sql);

System.out.println("Delete Success");

stmt.close();

} catch (SQLException e) {

e.printStackTrace();

}

}

public static Vector<CustomerVO> search(Connection conn, String sql){

Vector<CustomerVO> vector = null;

Statement stmt = null;

ResultSet rs = null;

try{

stmt = conn.createStatement();

rs = stmt.executeQuery(sql);

if(rs.next()){ //있다면

vector = new Vector<CustomerVO>(1,1); //동명이인이 있을 수도있어 (1) 대신 (1,1)

do{

CustomerVO c = new CustomerVO();

c.setGubun(rs.getInt("gubun"));

c.setTelnum(rs.getString("telnum"));

c.setIrum(rs.getString("irum"));

c.setGibon(rs.getInt("gibon"));

c.setFee(rs.getInt("fee"));

c.setTax(rs.getInt("tax"));

c.setTotal(rs.getInt("total"));

vector.addElement(c);

}while(rs.next());

}

rs.close();

stmt.close();

}catch(SQLException ex){

ex.printStackTrace();

}

return vector;

}

public static Vector<CustomerVO> select(Connection conn){

Statement stmt = null;

ResultSet rs = null;

Vector<CustomerVO> vector = new Vector<CustomerVO>(1,1);

try {

stmt = conn.createStatement();

String sql = "SELECT * FROM Telephone";

rs = stmt.executeQuery(sql);

while(rs.next()){

CustomerVO c = new CustomerVO();

c.setGubun(rs.getInt("gubun"));

c.setTelnum(rs.getString("telnum"));

c.setIrum(rs.getString("irum"));

c.setGibon(rs.getInt("gibon"));

c.setFee(rs.getInt("fee"));

c.setTax(rs.getInt("tax"));

c.setTotal(rs.getInt("total"));

vector.addElement(c);

}

rs.close();

stmt.close();

} catch (SQLException e) {

e.printStackTrace();

}

return vector;

}

public static void insert(Connection conn, CustomerVO c){

Statement stmt = null;

try {

stmt = conn.createStatement();

StringBuffer sb = new StringBuffer("INSERT INTO Telephone ");

sb.append("VALUES('" + c.getTelnum() + "'," + c.getGubun());

sb.append(",'" + c.getIrum() + "'," + c.getHowmany());

sb.append("," + c.getGibon() + "," + c.getFee() + "," + c.getTax());

sb.append("," + c.getTotal() + ")");

//System.out.println(sb.toString());

stmt.executeUpdate(sb.toString());

stmt.close();

} catch (SQLException e) {

e.printStackTrace();

}

}

}

ㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡ

리눅스에서 sqlite3설치.

버츄얼 우분투를 켜서 sudo apt-get update 캐시업데이트.

sudo apt-get install sqlite3 libsqlite3-dev 해서 설치.

mkdir SqliteRoom으로 폴더하나 만들어주고 SqliteRoom 폴더안으로 들어가서  sqlite3 test.db 를 하면 테이블을 입력하면 test.db가 만들어질 것이다.

SQLite 끝.


=========================================================================

Server

1. Machine 이 서버.

2. OS 가 서버.

3. Program 이 서버

4. Server Service Start

ㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡ

MYSQL 시작.

윈도우즈에서  http://www.mysql.com/ 접속.

Download 탭에서 MySQL Community Edition의 다운로드로 이동.

MySQL Community Server (GPL) 선택.

밑에 쪽의 Windows(x86,64-bit), MySQL INstaller MSI 다운로드 선택.

Windows (x86, 32-bit), MSI Installer 5.6.17 234.7M 다운로드. 누르면 로그인 사인업 등이 잇는데 밑에 no thanks 클릭하면 다운로드됨.

다시  MySQL Community Edition의 다운로드로 이동 해서 

MySQL Workbench (GPL) 다운로드 선택 후 Windows (x86, 32-bit), MSI Installer 6.1.4 30.0M 다운로드 클릭. no thanks까지

다시 전으로 가서 MySQL Connectors 선택하고 Connector/J 선택. Windows (x86, 32-bit), MSI Installer 5.1.30 6.1M 다운로드. no thanks까지

http://www.sqlgate.com/ 접속. Download 탭이동. 

SQLGate for MySQL Developer 3.3.1.0 04/01/2014 11.7 M   다운로드.

그리고 다운받은 mysql-installer-community-5.6.17.0.msi 를 설치.

Install누르고 next, skip후 next 선택. Developer Default 선택. 나머지는 안건드리고 next.  그리고 기본설정대로 하고 execute.

동의하고 계속 install. 다 되면 next. 그리고 execute(보면 connector/j와 mysql Workbench 가 들어있는 것을 볼 수 있다. 괜히 깔았넹)

next, next, port number가 3306번인데 아래 파이어월을 열어준다에 체크가되어있다. 마지막에 show advanced option 체크 next.

MySQL Root Password 는 javamysql 을 해줌. next.

Windows Service Name은 두고 Start the MySQL Server at System Startup 체크 해제. next. 바로 next. next. next.

star MySQL Workbench after Setup 체크해제. finish.

실행시키는 첫번째 방법은 관리자권한으로 도스창열어줌. net start mysql56 시작. net stop mysql56 스탑.

두번째는 제어판에가서 관리도구가서 services 에서 MySQL56을 start or stop. 더블클릭해서 들어가면 Startup type에 Manual로 바꿔줌(부팅할때 자동으로 안올라오게 하기위해)

환경변수설정창에서 Path를 보면 MySQL이 올라온것을 볼 수 있다. 

그리고 환경변수 설정창에서 Systme variables에서 new를 선택.

name = MYSQL_HOME, values = C:\Program Files\MySQL\MySQL Server 5.6 로 설정.

그리고 Path에서 마지막에 %MYSQL_HOME%\bin 를 추가해줌.

일반 커맨드창을 열어서 set path해서 설정해줌.

그리고 mysql -h localhost -u root -p 하고 비번 javamysql 치면 mysql로 접속됨.


show databases; 를치면 기본적으로 설치된 데이터베이스를 볼 수 있다.

use world 를 치면 데이터베이스가 바뀐다.

show tables;

desc city;

use test

show tables;

DESC mysql.user;

select host, user, password from mysql.user;  //아무리 관리자라도 패스워드는 볼 수 없음.

exit   //종료


MySQL Workbench 실행.

local instance를 누르고 비번 javamysql을 누르면 들어가짐.


다시 관리자 명령프롬프트 접속. mysql -u root -p 엔터 비번쓰고

use mysql 엔터

GRANT ALL PRIVILEGES ON *.* TO 'root'@'%' IDENTIFIED BY 'javamysql';    @뒤는 클라이언트 머신을 얘기하는거임.

flush privileges; 엔터

위와 같이 설정하면  MySQL Workbench에서 Database 탭에서 connect to database 해서 다른 컴퓨터에 접근가능.(안되면 처음 홈화면에서 +해서 접속하면 됨)

명령프롬프트에서 접속할 때는 mysql -h 아이피or컴퓨터이름 -u root -p 로 다른컴퓨터로 접속가능.


아까 받은 SQLGateforMySQLDev.exe  설치.

호스트 localhost, 사용자 root, 암호 javamysql, 암호저장체크, 데이터베이스 mysql(접근할데이터베이스), 문자집합 utf8, 날짜형식 default. 접속테스트 누르고 접속.



이클립스 접속 해서 sql explorer 에서 new profile 들어가서 add/edit driver에서 mysql drivers 을 edit해서

extra class path 에서 add  JARs를 C:\Program Files\MySQL\Connector J 5.1.29의 mysql-conn~~~~.jar파일 선택.

list driver눌러서 driver class name을 com.mysql.jdbc.Driver 선택.

Example URL은 jdbc:mysql://localhost:3306/test로 해줌.(자기것에 3306포트에 아무것도 없는 test를 지정) . ok. ok

Name은 MySQL 5.6 , Driver는 MySQL Driver

autoLogon선택해서 user는 root, password는 javamysql 하고 autocommit 하고 ok.

커넥트하고 

select * FROM world.City

where countrycode = 'KOR';

이렇게 해보던지, 아니면 우측 위에 test를 world로 바꿔서 검색을 하던지.

하면 결과값볼수 있고.


다시 전화요금관리프로그램으로 이동.

build Path-configuration buildPath에 들어가서 libraries 탭에서 external jars에서 C:\Program Files\MySQL\Connector J 5.1.29 에서  mysql-conn~~~~.jar파일 선택.

Main에서

import java.sql.Connection;

import java.sql.DriverManager;

import java.sql.SQLException;

import java.sql.Statement;


public class Main {

public static void main(String[] args) {

//2. Driver Loading

try {

Class.forName("com.mysql.jdbc.Driver");

System.out.println("Loading Success");

} catch (ClassNotFoundException e) {

System.out.println("Class Not Found");

}

//3. Connection

Connection conn = null;

String str = "jdbc:mysql://Win8-22:3306/test";  //내컴터이름과 포트번호

try{

conn = DriverManager.getConnection(str,"root","javamysql"); //아이디,비번 넣야함.

System.out.println("Connection Success");

}catch(SQLException ex){

System.out.println("Connection failure");

}

//4. Statement 객체 생성

Statement stmt = null;

try{

stmt = conn.createStatement();

//5. Query 실행

StringBuffer sb = new StringBuffer();

sb.append("CREATE TABLE telephone(");

sb.append("telnum    CHAR(8)  PRIMARY KEY, ");

sb.append("gubun   INTEGER   NOT NULL,");

sb.append("irum    VARCHAR(20)  NOT NULL,");

sb.append("howmany   INTEGER   NOT NULL,");

sb.append("gibon   INTEGER,");

sb.append("fee   INTEGER, ");

sb.append("tax   INTEGER, ");

sb.append("total  INTEGER)");

stmt.executeUpdate(sb.toString());

System.out.println("Table Creation Success");

}catch(SQLException ex){

ex.printStackTrace();

}

try{

if(stmt != null) stmt.close();

if(conn != null) conn.close();

}catch(SQLException ex){

ex.printStackTrace();

}

}

}

위와같이해서 로딩, 연결, 테이블까지 만들어줌.

그리고 dbinfo.properties 를

DBDRIVER=com.mysql.jdbc.Driver

DBURL=jdbc:mysql://localhost:3306/test

DBUSER=root

DBPWD=javamysql

이와 같이 변경해줌.


그리고 DBConnection은 user와 pwd를 다시 추가했으니 다시변경.

import java.io.FileInputStream;

import java.io.FileNotFoundException;

import java.io.IOException;

import java.sql.Connection;

import java.util.Properties;


public class DBConnection{

private Properties info = null;

private Connection conn = null;

public DBConnection(){

info = new Properties();

try{

info.load(new FileInputStream("dbinfo.properties"));

}catch(FileNotFoundException ex){ ex.printStackTrace(); 

}catch(IOException ex){ ex.printStackTrace(); }

}

public void loadDriver(){

try{

Class.forName(info.getProperty("DBDRIVER"));

}catch(ClassNotFoundException ex){

System.out.println("Class Not Found");

}

}

public void setConnection(){

String url = info.getProperty("DBURL");

String user = info.getProperty("DBUSER");

String pwd = info.getProperty("DBPWD");

try{

conn = java.sql.DriverManager.getConnection(url, user, pwd);

}catch(java.sql.SQLException ex){

System.out.println("Cannot Connect Access");

}

}

public Connection getConnection(){

if(this.conn != null) return this.conn;

else return null;

}

}

그리고 다시 실행해보면 실행이 잘된다.


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

ㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡ

우분투 폴더 복사.
복사한 우분투 켜서 sudo apt-get update
sudo apt-get install mysql-server mysql-client 엔터.
root password 쓰는 것이 뜨면 javamysql 써주고. 설치 끝.
확인하면 sudo netstat -tap | grep mysql 을 써서 확인.
sudo service mysql restart 엔터.
sudo gedit으로 열어서 /etc/mysql 에서 my.cnf를 열음.
[client]
port = 3306
이 부분 바로 아래에
default-charset=utf8  를 추가.
그리고 48라인
bind-address = 127.0.0.1 을 주석처리 앞에 #해서 #bind-address = 127.0.0.1 해줌. //이렇게 해야 다른머신에서 들어올 수 있음.
이게 안되네 default-charset=utf8  주석처리 해줌. #default_charset=utf8
그리고 mysql 치면 mysql로 들어올 수 있음. quit 해서 나와주고
mysql -u root -p 로 관리자 권한 로그인. 비번은 javamysql.
select host,user, password from mysql.user; 으로 보면. 계정없이 들어가는 것을 볼 수 있다. 이것은 보안에 상당한 위험을 줌.
delete from mysql.user where user = ''; 로 user 가 공백인 것을 삭제. 확인하면  지워진 것을 볼 수 있음. quit로 나오고.
mysql -u root -p 으로 접속후 flush privileges; 을 해서 프리빌리지해줌. quit 해서 다시 mysql쓰면 접속안됨. 이제 게스트계정으로는 접속 불가.
다시 mysql -u root -p으로 접속 비번쓰고.  GRANT ALL PRIVILEGES ON *.* TO 'root'@'%' IDENTIFIED BY 'javamysql';  해서 루트계정은 모든 권한을 줌
flush privileges; 해서 디비를 반영시키고 
exit 로 나와서  sudo service mysql restart 재시작.
그리고 다시 sudo gedit으로 my.cnf를 열어서 default-character-set=utf8 로 바꿔주고 sudo service mysql restart 해줌.

위에서 했던 것처럼. 우분투에서는 방화벽 3306을 풀고 MySQLWorkbench로 우분투에 접속해보고, 우분투에서는  mysql -h 접속할아이피 -u root -p 로 접속. 해본다.

sudo apt-get remove mysql-server mysql-client 로 삭제.(근데 서비스는 됨...)
첫번째 우분투 카피본 삭제.
-----------
두번째 우분투 카피본을 켜봄.
http://www.mysql.com/ 로 접속. Download 탭에가서
MySQL Community Edition (GPL) 의 다운로드 선택.
MySQL Community Server (GPL) 선택.
MySQL Community Server 5.6.17 에서 Select Platform: 을 Debian Linux로 선택하고.
Debian Linux 6.0 (x86, 32-bit), DEB 5.6.17 276.3M 다운로드 선택. no thanks.
그리고 구글에가서 libaio_0.3.104-1_i386.deb download 검색. libaio_0.3.104-1_i386.deb [6018 bytes] - Download Mirrors  사이트로 들어감.
2013-07-18  ftp://ftp.vss.spb.ru/pub/unix/oracle/libaio_0.3.104-1_i386.deb 선택해서 다운로드.
터미널켜서 먼저 sudo apt-get update 로 캐시업데이트.
cd Downloads로 이동. sudo apt-get install build-essential 하면 이미 깔려있넹.
sudo dpkg -i lib*.deb 로  libaio_0.3.104-1_i386.deb 설치.
sudo groupadd mysql
sudo useradd -r -g mysql mysql   //mysql계정을 만들면서 mysql 그룹을 만듬.
sudo dpkg -i mysql*.deb 로 mysql-5.6.17-debian6.0-i686.deb 을 설치.
ls /opt/ 명령어로 mysql 확인 가능.
소유권 변경:  sudo chown -R mysql:mysql /opt/mysql      //앞의 mysql계정:mysql그룹
ls -l /opt/mysql 으로 확인.
cd /opt/mysql/server-5.6 로 이동.  ls -l 쳐보면 계정과 그룹이 mysql로 바뀌어있음을 볼 수 있다.
sudo passwd mysql 을 쳐서 패스워드를 주자. mysql로 비번을 줌.
su mysql 하고 비번쓰는곳에도 mysql 그러면 시작됨.
pwd //위치확인
ls  //현재 폴더의 파일 확인
cd support -files 에 mysql-server 확인.
cd.. 해서 cd scripts 로 감.
./mysql_install_db --user=mysql    //이노디비설치
cd .. -> cd bin 이동. 
./mysqld_safe --user=mysql &  // &은 백그라운드파일~~ 
ps -ef | grep mysql    //현재프로세스에 올라와있는 목록 중에 mysql 들어가 있는 것만 필터
exit  로 나와주고.
cd support-files 로  들어가서. sudo cp ./mysql.server /etc/init.d/mysqld   로 카피.
데몬서비스를 올렸으니 sudo update-rc.d mysqld defaults   업데이트하고, //앞으로 mysqld 임.
cd 로 내 집에가서 sudo service mysqld start  스타트
sudo service mysqld restart    리스타트.
ps -ef | grep mysqld 로 서비스가 잘돌아가는 지 확인.
sudo service mysqld stop  스탑
sudo service mysqld restart  리스타트
sudo service mysqld start  스타트
sudo service mysqld status  상태확인 . 이렇게 네가지.
sudo gedit /etc/profile 로 들어가서 .
#--------------------------------------------------
# Java Settings
#--------------------------------------------------

JAVA_HOME=/usr/lib/jvm/jdk1.7.0_51
MYSQL_HOME=/opt/mysql/server-5.6
CLASSPATH=.:/usr/lib/jvm/jdk1.7.0_51/lib/tools.jar
PATH=$JAVA_HOME/bin/:$PATH:$MYSQL_HOME/bin

export JAVA_HOME
export MYSQL_HOME
export CLASSPATH
export PATH
위에서 추가한 건 MYSQL관련부분.
확인 해보면  source /etc/profile
echo $MYSQL_HOME
echo $PATH
which mysql
그리고 mysql치면 로그인되는데 게스트가 로그인이 안되게 해보자.
일단 터미널에서 mysqladmin -u root password javamysql 해서 비번을 정해주고.
mysql -u root -p 로 접속. 비번써주고.
select host,user, password from mysql.user; 으로 user가 공백인 것 확인.
delete from mysql.user WHERE user='';  로 user가 공백인 것 삭제.
select host,user, password from mysql.user; 로 보면 삭제 된 것을 볼 수 있다.
UPDATE mysql.user SET password=password('javamysql') WHERE user='root'; 로 user가 root인 계정의 비번을 javamysql로 바꿔줌. password의 함수로 인코딩해서 보이지않게 해줌.
flush privileges;   권한 적용. quit로 나가서   mysql -h 127.0.0.1 -u root -p 을 쳐서 로컬호스트로 접속을 하게 하면 비번을 적어야하는 것을 볼 수 있다.
또 접속해서 GRANT ALL PRIVILEGES ON *.* TO 'root'@'%' IDENTIFIED BY 'javamysql';  해서 루트계정은 모든 권한을 줌
flush privileges; 로 마무리.
-----------------------
다시 전화요금관리프로그램가서 
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;

public class Main {
public static void main(String[] args) {
//2. Driver Loading
try {
Class.forName("com.mysql.jdbc.Driver");
System.out.println("Loading Success");
} catch (ClassNotFoundException e) {
System.out.println("Class Not Found");
}
//3. Connection
Connection conn = null;
String str = "jdbc:mysql://192.168.56.130:3306/test";  //리눅스 컴터 아이피.
try{
conn = DriverManager.getConnection(str,"root","javamysql"); //아이디,비번 넣야함.
System.out.println("Connection Success");
}catch(SQLException ex){
System.out.println("Connection failure");
}
//4. Statement 객체 생성
Statement stmt = null;
try{
stmt = conn.createStatement();
//5. Query 실행
StringBuffer sb = new StringBuffer();
sb.append("CREATE TABLE telephone(");
sb.append("telnum    CHAR(8)  PRIMARY KEY, ");
sb.append("gubun   INTEGER   NOT NULL,");
sb.append("irum    VARCHAR(20)  NOT NULL,");
sb.append("howmany   INTEGER   NOT NULL,");
sb.append("gibon   INTEGER,");
sb.append("fee   INTEGER, ");
sb.append("tax   INTEGER, ");
sb.append("total  INTEGER)");
stmt.executeUpdate(sb.toString());
System.out.println("Table Creation Success");
}catch(SQLException ex){
ex.printStackTrace();
}
try{
if(stmt != null) stmt.close();
if(conn != null) conn.close();
}catch(SQLException ex){
ex.printStackTrace();
}
}
}
로 실행 시켜주고.
dbinfo.properties을 아래와 같이 바꿔줌.
DBDRIVER=com.mysql.jdbc.Driver
DBURL=jdbc:mysql://192.168.56.130:3306/test
DBUSER=root
DBPWD=javamysql

CustomerDAO.java 에서 Telephone을 telephone으로 바꿔준다.
실행해보면 출력에서 한글이 화면이 깨진다.
sudo gedit 해서 열어서 /opt/mysql/server-5.6에서 my.cnf 열음.
4라인 [mysqld] 위에 
[client]
default-character-set=utf8  을 넣어준다.
설정이 바뀌었으니  sudo service mysqld restart 로 재시작해줌.  다시 실행해도 한글 안됨.
다시 my.cnf에 들어가서 default-character-set=utf8 를 주석처리 #default-character-set=utf8  해줌.
다른방법:
import java.io.UnsupportedEncodingException;

public class Utility {
public static String kotoen(String ko){
String en = null;
try{
en = new String(ko.getBytes("KSC5601"), "ISO8859_1");
}catch(UnsupportedEncodingException ex){}
return en;
}
public static String entoko(String en){
String ko = null;
try{
ko = new String(en.getBytes("ISO8859_1"), "KSC5601");
}catch(UnsupportedEncodingException ex){}
return ko;
}
}
를 추가해주고. 
CustomerDAO를 아래와 같이 바꿔줌.
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Vector;


public class CustomerDAO {
public static void delete(Connection conn, String sql){
Statement stmt = null;
try {
stmt = conn.createStatement();
stmt.executeUpdate(sql);
System.out.println("Delete Success");
stmt.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
public static Vector<CustomerVO> search(Connection conn, String sql){
Vector<CustomerVO> vector = null;
Statement stmt = null;
ResultSet rs = null;
try{
stmt = conn.createStatement();
rs = stmt.executeQuery(sql);
if(rs.next()){  //있다면
vector = new Vector<CustomerVO>(1,1);
do{
CustomerVO c = new CustomerVO();
c.setGubun(rs.getInt("gubun"));
c.setTelnum(rs.getString("telnum"));
c.setIrum(Utility.entoko(rs.getString("irum")));
c.setGibon(rs.getInt("gibon"));
c.setFee(rs.getInt("fee"));
c.setTax(rs.getInt("tax"));
c.setTotal(rs.getInt("total"));
vector.addElement(c);
}while(rs.next());
}
rs.close();
stmt.close();
}catch(SQLException ex){
ex.printStackTrace();
}
return vector;
}
public static Vector<CustomerVO> select(Connection conn){
Statement stmt = null;
ResultSet rs = null;
Vector<CustomerVO> vector = new Vector<CustomerVO>(1,1);
try {
stmt = conn.createStatement();
String sql = "SELECT * FROM telephone";
rs = stmt.executeQuery(sql);
while(rs.next()){
CustomerVO c = new CustomerVO();
c.setGubun(rs.getInt("gubun"));
c.setTelnum(rs.getString("telnum"));
c.setIrum(Utility.entoko(rs.getString("irum")));
c.setGibon(rs.getInt("gibon"));
c.setFee(rs.getInt("fee"));
c.setTax(rs.getInt("tax"));
c.setTotal(rs.getInt("total"));
vector.addElement(c);
}
rs.close();
stmt.close();
} catch (SQLException e) {
e.printStackTrace();
}
return vector;
}
public static void insert(Connection conn, CustomerVO c){
Statement stmt = null;
try {
stmt = conn.createStatement();
StringBuffer sb = new StringBuffer("INSERT INTO telephone ");
sb.append("VALUES('" + c.getTelnum() + "'," + c.getGubun());
sb.append(",'" + Utility.kotoen(c.getIrum()) + "'," + c.getHowmany());
sb.append("," + c.getGibon() + "," + c.getFee() + "," + c.getTax());
sb.append("," + c.getTotal() + ")");
//System.out.println(sb.toString());
stmt.executeUpdate(sb.toString());
stmt.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
이렇게 하면한글이 출력시 화면이 깨지지 않음.
================================================================================================
ㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡ
CentOS 설치. 
typical-> ISO image 를 centos iso파일 선택. 비밀번호 아무거나 주고 next
경로 지정해주고   50GB/single file선택.
customize hardware 눌러서 메모리 2GB 코어4개 선택. automaticaly 체크 해제하고 
edit 눌러 CD/DVD2 삭제해주고  CD/DVD 경로를  centos ISO 파일 지정해주고.
설치 페이지에서 맨위 Install or upgrade 선택. 
skip 선택.
next-> English next -> next -> Basic ~~ next -> yes discard any data -> name 은 CentOS-22 next ->Seoul next
->password 는 자기꺼쓰고 next -> create custom Layout 선택.
Free눌러서 create ->standard create
systme type : swap, size: 2048 , fixed size 선택
다시 free 눌러서 create ->standard create 
Mount point : /boot , size 512, fixed size 선택
다시 free 눌러서 create ->standard create
Mount point : / , File to maximum allowable size  선택
next -> format -> write change to disk , next
-> next -> Desktop 선택 next -> 다 돼면 reboot ->foward x2
-> username ~~ 다 써주고 -> yes
->syncornize~~~ 체크해서 하나 선택후 next -> Enable Kdump 체크해제 fisnih yes
다 설치되면 centos 는 기본적으로 네트웍이 안되어 네트워크를 눌러서 eth0을 눌러 잡아줘야함.
system-preference-Input method  Enable 체크해서 Input method prefrence 눌러서 
Input method 탭에서 코리안 추가 로그아웃후 로그인하면 ctrl+space로 한글변환가능




 









+ Recent posts