13 December 2010

java JDBC MySQL Connect

java JDBC MySQL Connect Table: test
ID Name
1 A
2 B
3 C

import java.io.File;
import java.sql.*;
import java.sql.DriverManager;
import java.sql.SQLException;

public class Main {   
    public static void main(String args[]) {
        Connection con = null;
        try {
            Class.forName("com.mysql.jdbc.Driver");
            con = DriverManager.getConnection("jdbc:mysql://localhost","USERNAME", "PASSWORD");
            Statement st = con.createStatement();
            ResultSet rs = st.executeQuery("select * from test");
            int count = 0;
            while(rs.next())
            {
                System.out.println("ID : " + rs.getString(0));
                System.out.println("NAME : " + rs.getString(1));
                count++;
            }
            System.out.println("sum = "+count);
            
            } catch(Exception e) {
            e.printStackTrace();
            System.out.println("Exception: " + e.getMessage());
            } finally {
            try {
                if(con != null)
                con.close();
        } catch(SQLException e) {}
        }
    }
}

11 December 2010

List ชื่อไฟล์ใน Directory - java

List ชื่อไฟล์ใน Directory ด้วย java อ่านชื่อไฟล์ทั้งหมดใน Directory ตัวอย่าง แสดงเฉพาะ .txt และ .TXT
import java.io.File;
public class ListFiles
{
    public static void main(String[] args)
    {
        // Directory path here
        String path = ".";
        String files_name;
        File folder = new File(path);
        File[] listOfFiles = folder.listFiles();
        for (int i = 0; i < listOfFiles.length; i++)
        {
            if (listOfFiles[i].isFile())
            {
                files_name = listOfFiles[i].getName();
                if (files_name.endsWith(".txt") || files_name.endsWith(".TXT"))
                {
                    System.out.println(files_name);
                }
            }
        }
    }
}

Twitter Delicious Facebook Digg Stumbleupon Favorites More

 
Blog by Chagridsada Boonthus | http://chagridsada.blogspot.com/