1. 程式人生 > >JDBC連線資料庫程式碼 (一) -- 一個簡單的獲取資料庫表單

JDBC連線資料庫程式碼 (一) -- 一個簡單的獲取資料庫表單

package com.nenu.www;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;

import java.sql.Statement;

public class JdbcConn {
	
	public static void main(String[] args) {
		
		try {
			Class.forName("com.mysql.jdbc.Driver");//匯入驅動(jar包)
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
		
		Connection conn = null; 
		try {
			conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/test", "root", "root");//建立連線
		} catch (SQLException e) {
			e.printStackTrace();
		}
		
		String sql = "select name,email,dob from student";//建立SQL語句
		
		try {
			Statement stmt = conn.createStatement();
			ResultSet rs = stmt.executeQuery(sql);
			//cursor
			while(rs.next()){
				String name = rs.getString(1);
				String email = rs.getString(2);
				String dob = rs.getString(3);
				System.out.println(name+" , "+email+" , "+dob);
				
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}finally{
			if(conn!=null)
				try {
					conn.close();//關閉連線
				} catch (SQLException e) {
					e.printStackTrace();
				}	
		}
		
		
	}
}