1. 程式人生 > >Eclipse連線資料庫

Eclipse連線資料庫

//載入器
public void getConnection() {
	try {
		Class.forName("com.mysql.jdbc.Driver");
		conn=DriverManager.getConnection("jdbc:mysql://localhost:3306/root", "root", "1234");
	} catch (ClassNotFoundException e) {
		e.printStackTrace();
	} catch (SQLException e) {
		e.printStackTrace();
	}
}
//增刪改
public int execustSQL(String sql,Object... obj) {
	this.getConnection();
	int count = -1;
	try {
		this.pstmt = conn.prepareStatement(sql);
		for(int i=0;i<obj.length;i++) {
			this.pstmt.setObject(i+1, obj[i]);
		}
		pstmt.executeUpdate();
	} catch (SQLException e) {
		e.printStackTrace();
	}
	return count;
}
//查詢
public ResultSet executeQSL(String sql,Object... obj) {
	this.getConnection();
	try {
		this.pstmt = conn.prepareStatement(sql);
		for(int i=0;i<obj.length;i++) {
			pstmt.setObject(i+1, obj[i]);
		}
		rs = pstmt.executeQuery();
	} catch (SQLException e) {
		e.printStackTrace();
	}
	return rs;
	
}
//關閉流
public void closeAll() {
	if(rs!=null) {
		try {
			rs.close();
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}
	if(pstmt!=null) {
		try {
			pstmt.close();
		} catch (SQLException e) {
			e.printStackTrace();
		}
		if(conn!=null) {
			try {
				conn.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}

}
}
}