1. 程式人生 > >Java程式通過JDBC連線遠端資料庫MySQL

Java程式通過JDBC連線遠端資料庫MySQL

程式碼如下:

import java.sql.*;
public class jdbc {
	
 @SuppressWarnings("unused")
public static void main(String[] args) {
		// TODO Auto-generated method stub
	 JdbcConnection jdbcConnection = new JdbcConnection();
	}

}
//定義一個連線類
class JdbcConnection
{
	//建立一個用於連線的物件
	
	Connection ct = null;
	
	//建立一個用於傳送sql語句的物件
	PreparedStatement ps = null;
	//建立一個用於接收結果集的物件
	ResultSet rs = null;
	//預設建構函式
	public JdbcConnection()
	{
		try {
			//載入驅動
			Class.forName("org.gjt.mm.mysql.Driver");
			//得到連線
			ct = DriverManager.getConnection
				("jdbc:mysql://46.77.201.185:3306/SMOS?user=root&password=wtuliumeng&useUnicod e=true&characterEncoding=8859_1" );   
					  
			//查詢
			ps = ct.prepareStatement("select * from student");
			//得到結果
			rs = ps.executeQuery();
			//迴圈輸出
			while(rs.next())
			{
				String a = rs.getString(1);
				String b = rs.getString(2);
				System.out.println(a + " " + b);
			}
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}finally
		{
			try {
				//關閉資源
				if(rs != null)
				{
					rs.close();
				}
				if(ps != null)
				{
					ps.close();
				}
				if(ct != null)
				{
					ct.close();
				}
			} catch (Exception e2) {
				// TODO: handle exception
				e2.printStackTrace();
			}
			
		}
		
	}
}