2015年8月23日 星期日

JDBC 連結資料庫

利用 JDBC 與資料庫連結:
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

public class ConnectionDemo {
    public static void main(String[] args)
                  throws ClassNotFoundException{
        
        Class.forName("com.mysql.jdbc.Driver");
        
        String url = "jdbc:mysql://localhost:3306/directory"; 
        String dbaccount = "directory";
        String dbpassword = "a123456";
        
        try(Connection conn = DriverManager.getConnection(url,
                 dbaccount, dbpassword)){
           
            if (!conn.isClosed()){
                System.out.println("資料庫連結成功....");
            }
            
        } catch (SQLException ex) {
           System.out.println("資料庫連結失敗....");
        }
    }
}

MySQL 的範例資料庫 directory,可以利用下列語法建立起來:

CREATE DATABASE  IF NOT EXISTS `directory`;
USE `directory`;

DROP TABLE IF EXISTS `users`;
CREATE TABLE `users` (
  `no` int(11) NOT NULL AUTO_INCREMENT,
  `userName` varchar(100) NOT NULL,
  `userEmail` varchar(100) NOT NULL,
  PRIMARY KEY (`no`)
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8;

LOCK TABLES `users` WRITE;
INSERT INTO `users` VALUES (1,'test','test@localhost'),
       (2,'hello','hello@localhost.domain'),(3,'world','world@test.123');
UNLOCK TABLES;