JDBC連接訪問MySQL數據庫

package com.lian.jdbc;

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

public class ConnectMySQL {
	
	/*
	 * 數據庫的連接工具類
	 */
	private static final String Driver = "com.mysql.jdbc.Driver";
	private static final String DBURL = "jdbc:mysql://localhost:3306/db_user";
	private static final String UserName = "root";
	private static final String passWord = "root";
	
	private static Connection conn = null;
	
	/*
	 * 加載及註冊JDBC驅動程序
	 */
	public ConnectMySQL() {
		try {
			Class.forName(Driver);
			System.out.println("Success load Mysql Driver!");	
		} catch (ClassNotFoundException e) {
			System.out.println("Error load Mysql Driver!");
			e.printStackTrace();
		} 
	}
	
	/*
	 * 建立數據庫的連接
	 * @return
	 */
	public static Connection getConnection() {
		try {
			conn = DriverManager.getConnection(DBURL, UserName, passWord);
			System.out.println("Success connect Mysql Server!");
		} catch (SQLException e) {
			System.out.println("No connect Mysql Server!");
			e.printStackTrace();
		}
		return conn;	
	}	

}
 
package com.lian.jdbc;

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

public class TestJDBC {

	private static Connection conn = null;
	private static Statement stmt = null;
	private static ResultSet rs = null;
	
	/*
	 *測試JDBC連接MySQL
	 * @return args
	 */
	public static void main(String[] args) {

		ConnectMySQL connectMySQL = new ConnectMySQL();
		conn = ConnectMySQL.getConnection();
		try {
			stmt = conn.createStatement();//創建Statement對象,準備執行SQL語句
			rs = stmt.executeQuery("select * from user");//執行SQL語句
			//結果處理
			while (rs.next()) {
				String userName = rs.getString("userName");
				String phone = rs.getString("phone");
				System.out.println("userName:" + userName + "  " + "phone:" + phone);
			}
		} catch (SQLException e) {
			System.out.print("No data!");
			e.printStackTrace();
		} finally {
			// 釋放資源
			try {
				if (rs == null) rs.close();
				if (stmt == null) stmt.close();
				if (conn == null) conn.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
	}
	
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章